Last active
December 3, 2019 20:43
-
-
Save forivall/b8cba41b864cf8209e360c1e7e7d5a92 to your computer and use it in GitHub Desktop.
type helper
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
export const isTypeByProp = <T>(k: NonNullableProp<T>) => ( | |
obj: Partial<T> | |
// tslint:disable-next-line: triple-equals | |
): obj is T => obj[k as keyof T] != null; | |
type NonNullableProp<T> = { | |
[K in KeyOf<T>]: T extends Record<K, any> ? K : never; | |
}[KeyOf<T>]; | |
type KeyOf<T> = Extract<IfUnknown<KnownKeys<T>, keyof T>, keyof any>; | |
type IfUnknown<T, U> = unknown extends T ? T : U; | |
// https://stackoverflow.com/a/51956054/490829 | |
type KnownKeys<T> = { | |
[K in keyof T]: string extends K ? never : number extends K ? never : K; | |
} extends { [_ in keyof T]: infer U } | |
? U | |
: never; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment