Last active
January 17, 2021 23:25
-
-
Save pushkine/a908f986c54d7a4e960bec24114348b5 to your computer and use it in GitHub Desktop.
Collection of useful Typescript types
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
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