Skip to content

Instantly share code, notes, and snippets.

@forivall
Last active December 3, 2019 20:43
Show Gist options
  • Save forivall/b8cba41b864cf8209e360c1e7e7d5a92 to your computer and use it in GitHub Desktop.
Save forivall/b8cba41b864cf8209e360c1e7e7d5a92 to your computer and use it in GitHub Desktop.
type helper
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