Skip to content

Instantly share code, notes, and snippets.

@mauriciord
Forked from staltz/comment.md
Created November 7, 2019 14:41
Show Gist options
  • Save mauriciord/26031da10addb4f398c386897650e352 to your computer and use it in GitHub Desktop.
Save mauriciord/26031da10addb4f398c386897650e352 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