[Typescript] Using 'Pick' to create a sub-type from original type
typescript to 39 from type Using create
2023-09-14 09:00:48 时间
There might be cases where you have selective data for your entities. Let's say that you are building a public API endpoint to get all the registered users from your users
collection. Now there might be sensitive data in your User
entity type that you may not want to return in the response. In such cases, Pick
can help you be selective and get only the properties you need.
In this lesson, we will learn how to extract properties from a type and create a new type from it.
interface Item { name: string; description: string; price: number; currency: string; image: string; }; type ItemPreview = Pick<Item, "name" | "image">; const item: Item = { name: "Macbook", description: "Macbook Pro 2019", price: 2138, currency: "USD", image: "https://cdn.apple.com/mbpro.png" }; const itemPreview: ItemPreview = { name: item.name, image: item.image, description: item.description }; console.log(itemPreview); console.log(item);
相关文章
- [Typescript] Use Function Overloads to Avoid Returning undefined
- [Typescript] 136. Medium - Object to Union
- [Typescript] Using Generic Context to Avoid Distributivity in Conditional Types
- [Typescript] 104. Hard - Tuple to Enum Object
- [Typescript] 79. Medium - MapTypes
- [Typescript] Tips: Assign local variables to default generic slots to dry up your code and improve performance
- [Typescript] 45. Medium - MinusOne (Solution to solve max number of iteration by tail call)
- [Typescript challenge] 19. Medium - Tuple to Union
- [Typescript Challenges] 7. Easy - Awaited
- [Typescript Challenges] 3. Easy - Tuple to Object
- [Typescript] When to use generic type?
- [TypeScript] as const, force immutability for Object type
- [TypeScript] Catch unsafe use of "this" in TypeScript functions
- [TypeScript] Using Assertion to Convert Types in TypeScript
- [Typescript] Force to valid the type by using Valid branded type
- [Typescript] Map a Discriminated Union to an Object
- [Typescript] 110. Hard - Union to Tuple
- [Typescript] Tips: Turn a module into a type
- [Typescript] 42. Medium - Remove Index Signature
- [Typescript + React] Tips: Write your own 'PropsFrom' helper to extract props from any React component
- [Typescript] Tips: Use 'in' operator to transform a union to another union(watched)
- [Typescript challenge] 20. Medium - Chainable Options
- [Typescript] Tuple type usage example & Discriminated Unions
- [Typescript] When to use generic type?
- [TypeScript] Model Alternatives with Discriminated Union Types in TypeScript
- [TypeScript] Using Assertion to Convert Types in TypeScript
- [TypeScript] Using Interfaces to Describe Types in TypeScript
- 2022 typescript史上最强学习入门文章(2w字)