Skip to content

Instantly share code, notes, and snippets.

@mateja176
Last active September 21, 2021 15:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mateja176/e4ecb395e8db4e3e98ab6c9ee60d1053 to your computer and use it in GitHub Desktop.
Save mateja176/e4ecb395e8db4e3e98ab6c9ee60d1053 to your computer and use it in GitHub Desktop.
type RequiredKeys<O extends unknown> = {
// eslint-disable-next-line @typescript-eslint/ban-types
[Key in keyof O]: {} extends Pick<O, Key> ? never : Key;
}[keyof O];
type DeepPick<O extends unknown, Keys extends unknown[]> = Keys extends [
keyof O,
...infer Rest
]
? Keys[0] extends RequiredKeys<O>
? { [K in Keys[0]]: DeepPick<O[Keys[0]], Rest> }
: { [K in Keys[0]]?: DeepPick<O[Keys[0]], Rest> }
: O;
type A = { a: 1; b: 2 };
type A2 = DeepPick<A, ['a']>;
type A3 = DeepPick<A, ['b']>;
type A4 = DeepPick<A, ['c']>;
type A5 = DeepPick<A, [1]>;
type B = { a: 1; b: { c: 2; d: 3 } };
type B1 = DeepPick<B, ['b', 'c']>;
type B2 = DeepPick<B, ['b', 'e']>;
type C = { a: 1; b: { c: 2; d: { e: 3; f: 4 } } };
type C1 = DeepPick<C, ['b', 'c']>;
type C2 = DeepPick<C, ['b', 'd']>;
type C3 = DeepPick<C, ['b', 'd', 'e']>;
type C4 = DeepPick<C, ['b', 'd', 'g']>;
type D = { a: 1; b?: { c?: 2; d: { e?: 3; f?: 4 } } | null };
type D1 = DeepPick<D, ['b', 'c']>;
type D2 = DeepPick<D, ['b', 'd']>;
type D3 = DeepPick<D, ['b', 'd', 'e']>;
type D4 = DeepPick<D, ['b', 'd', 'e', 'f']>;
type D5 = DeepPick<D, ['b', 'd', 'g']>;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment