Created
March 15, 2021 04:04
-
-
Save mscolnick/09c3c7015c78f1a85b9822b745d1a7d1 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// Awaiting promises | |
type Awaited<T> = | |
T extends null | undefined ? T : | |
T extends PromiseLike<infer U> ? Awaited<U> : | |
T; | |
type P1 = Awaited<Promise<string>>; // string | |
type P2 = Awaited<Promise<Promise<string>>>; // string | |
type P3 = Awaited<Promise<string | Promise<Promise<number> | undefined>>; // string | number | undefined | |
// Flattening arrays | |
type Flatten<T extends readonly unknown[]> = T extends unknown[] ? _Flatten<T>[] : readonly _Flatten<T>[]; | |
type _Flatten<T> = T extends readonly (infer U)[] ? _Flatten<U> : T; | |
type InfiniteArray<T> = InfiniteArray<T>[]; | |
type A1 = Flatten<string[][][]>; // string[] | |
type A2 = Flatten<string[][] | readonly (number[] | boolean[][])[]>; // string[] | readonly (number | boolean)[] | |
type A3 = Flatten<InfiniteArray<string>>; | |
type A4 = A3[0]; // Infinite depth error | |
// Repeating tuples | |
type TupleOf<T, N extends number> = N extends N ? number extends N ? T[] : _TupleOf<T, N, []> : never; | |
type _TupleOf<T, N extends number, R extends unknown[]> = R['length'] extends N ? R : _TupleOf<T, N, [T, ...R]>; | |
type T1 = TupleOf<string, 3>; // [string, string, string] | |
type T2 = TupleOf<number, 0 | 2 | 4>; // [] | [number, number] | [number, number, number, number] | |
type T3 = TupleOf<number, number>; // number[] | |
type T4 = TupleOf<number, 100>; // Depth error |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment