Skip to content

Instantly share code, notes, and snippets.

@mardukbp
Forked from staltz/comment.md
Created April 14, 2021 17:03
Show Gist options
  • Save mardukbp/c0b4c8d55ff13d52d52d6dc784eb233c to your computer and use it in GitHub Desktop.
Save mardukbp/c0b4c8d55ff13d52d52d6dc784eb233c to your computer and use it in GitHub Desktop.
Nested Pick<T, K> in TypeScript 2.2

TypeScript supports Pick to allow you to get a "subset" object type of a given type, but there is no built-in Pick for deeper nested fields.

If you have a function that takes a large object as argument, but you don't use all of its fields, you can use Pick, Pick2, Pick3, etc to narrow down the input type to be only just what you need. This will make it easier to test your function, because when mocking the input object, you don't need to pass all fields of the "large" object.

type UserWithOnlyAddress = Pick<User, 'address'>;
type User = {
id: number,
name: string,
address: {
street: string,
zipcode: string,
geo: {
lat: string,
lng: string,
},
},
};
type UserWithOnlyStreetAddress = Pick2<User, 'address', 'street'>;
type User = {
id: number,
name: string,
address: {
street: string,
zipcode: string,
geo: {
lat: string,
lng: string,
},
},
};
type Pick2<T, K1 extends keyof T, K2 extends keyof T[K1]> = {
[P1 in K1]: {
[P2 in K2]: (T[K1])[P2];
};
};
type UserWithOnlyGeoLat = Pick3<User, 'address', 'geo', 'lat'>;
type User = {
id: number,
name: string,
address: {
street: string,
zipcode: string,
geo: {
lat: string,
lng: string,
},
},
};
type Pick3<T, K1 extends keyof T, K2 extends keyof T[K1], K3 extends keyof T[K1][K2]> = {
[P1 in K1]: {
[P2 in K2]: {
[P3 in K3]: ((T[K1])[K2])[P3];
};
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment