Concept Flow - Pick type
Define original type
Specify keys to pick
Apply Pick<Type, Keys>
New type with only picked keys
Use new type in code
Pick type creates a new type by selecting specific keys from an existing type.
type Person = {
name: string;
age: number;
city: string;
};
type PersonNameAge = Pick<Person, "name" | "age">;| Step | Action | Evaluation | Result |
|---|---|---|---|
| 1 | Define type Person | Person has keys: name, age, city | Person = {name: string; age: number; city: string;} |
| 2 | Specify keys to pick | Keys chosen: 'name' and 'age' | 'name' | 'age' |
| 3 | Apply Pick<Person, 'name' | 'age'> | New type includes only 'name' and 'age' keys | PersonNameAge = {name: string; age: number;} |
| 4 | Use PersonNameAge in code | PersonNameAge has only name and age properties | Valid to assign {name: 'Alice', age: 30} |
| 5 | Try to assign city property | Error: city does not exist on PersonNameAge | TypeScript error |
| Variable | Start | After Step 3 | Final |
|---|---|---|---|
| Person | {name, age, city} | {name, age, city} | {name: string; age: number; city: string;} |
| Keys to pick | undefined | 'name' | 'age' | 'name' | 'age' |
| PersonNameAge | undefined | {name: string; age: number} | {name: string; age: number} |
Pick<Type, Keys> creates a new type by selecting only Keys from Type. Syntax: type NewType = Pick<OriginalType, 'key1' | 'key2'>; Result: NewType has only the chosen keys with their original types. Useful to create smaller types from bigger ones. Keys must exist in the original type.
Pick type do in TypeScript?PersonName with only name and age properties from Person using Pick?interface User { id: number; name: string; email: string; } and type UserPreview = Pick;, what is the type of userPreview in this code?const userPreview: UserPreview = { id: 1, name: 'Alice' };interface Product { id: number; name: string; price: number; }
type ProductInfo = Pick;interface Employee { id: number; name: string; department: string; salary: number; }. You want to create a type EmployeeSummary that includes only id, name, and a new property departmentCode which is a string. How can you do this using Pick and adding the new property?Pass the test and this pattern moves unknown