Implementing a Custom Utility Type: Pick
Implement the built-in Pick<T, K> generic without using it.
Pick is a utility type in TypeScript that allows you to create a new type by picking a set of properties from an existing type.
Syntax:
Pick<Type, Keys>
Type
: The type from which properties will be pickedKeys
: A union of property names to pick from the original type
Example
type User = {
id: number;
name: string;
email: string;
age: number;
};
type BasicUserInfo = Pick<User, 'id' | 'name'>;
// Equivalent to:
type BasicUserInfo = {
id: number;
name: string;
};
// Usage
const user: BasicUserInfo = {
id: 1,
name: "John Doe",
};
Solution
The custom Pick type uses a mapped type to iterate over a subset of keys (K) from a given type (T), creating a new type with only those selected properties.
It ensures type safety by restricting K to valid keys of T using K extends keyof T
.
type User = {
id: number;
name: string;
email: string;
age: number;
};
type MyPick<T, K extends keyof T> = {
[P in K]: T[P];
};
// Usage
const user: MyPick<User, "name" | "email"> = {
name: "John Doe",
email: "john@example.com",
};
console.log(user)
/*
Output:
{
"name": "John Doe",
"email": "john@example.com"
}
*/
T
: is the original type from which properties will be pickedK extends keyof T
: ensures K is a valid subset of keys from T[P in K]: T[P]
: constructs a new type by iterating over the keys in K and assigning the corresponding value types from T
Summary
- Use
Pick
when you want to create a new type by picking a set of properties from an existing type - Use cases: Creating a new type with a subset of properties from an existing type