Created
February 17, 2023 14:47
-
-
Save RikoKami/5bc28109a6acda901a1b8bc2bcc7d654 to your computer and use it in GitHub Desktop.
picking up the branches of an object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type ExtractKeys<T> = { | |
[K in keyof T & string]: T[K] extends any[] | |
? `${K}` | |
: T[K] extends object | |
? | |
`${K}` | `${K}.${ExtractKeys<T[K]>}` | |
: `${K}`; | |
}[keyof T & string]; | |
type ExtractNonDateKeys<T> = { | |
[K in keyof T & string]: T[K] extends any[] | |
? `${K}` | |
: T[K] extends object | |
? T[K] extends Date | |
? `${K}` | |
: `${K}.${ExtractKeys<T[K]>}` | |
: `${K}`; | |
}[keyof T & string]; | |
type GetObject<T extends Record<PropertyKey, any>, S extends string> = S extends keyof T | |
? { | |
[Key in S]: T[Key]; | |
} | |
: S extends `${infer A}.${infer Rest}` | |
? { | |
[Key in A]: Rest extends [] ? T[A] : GetObject<T[A], Rest>; | |
} | |
: never; | |
type UnionToIntersection<U> = (U extends U ? (arg: U) => void : never) extends ( | |
arg: infer R, | |
) => void | |
? R | |
: never; | |
type DeepPick< | |
T extends Record<string, any>, | |
U extends ExtractNonDateKeys<T> | |
> = UnionToIntersection<U extends U ? GetObject<T, U> : never>; | |
type myObject = { | |
name: string, | |
age: number, | |
props: { | |
prop1: string, | |
prop2: { | |
other: string, | |
}, | |
}, | |
} | |
type t1 = DeepPick<myObject, "props.prop1" | "props.prop2" | "name"> | |
type t2 = DeepPick<myObject, "age"> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment