Skip to content

Instantly share code, notes, and snippets.

@pushkine
Last active January 17, 2021 23:25
Show Gist options
  • Save pushkine/a908f986c54d7a4e960bec24114348b5 to your computer and use it in GitHub Desktop.
Save pushkine/a908f986c54d7a4e960bec24114348b5 to your computer and use it in GitHub Desktop.
Collection of useful Typescript types
declare global {
interface ObjectConstructor {
keys<O extends object>(o: O): (keyof O & string)[];
}
}
/**
* Returns tuple types that include every string in union
* TupleUnion<keyof { bar: string; leet: number }>;
* ["bar", "leet"] | ["leet", "bar"];
*/
type TupleUnion<U extends string, R extends string[] = []> = {
[S in U]: Exclude<U, S> extends never ? [...R, S] : TupleUnion<Exclude<U, S>, [...R, S]>;
}[U] & string[];
/**
* Inline type predicate (removed by bundler)
* if (foo.nodeType === 1 && Narrow<Element>(foo)) { /* forces <typeof foo> to be <Element> in this block */ }
*/
const Narrow = <T>(v): v is T => true;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment