Skip to content

Instantly share code, notes, and snippets.

@Alia5

Alia5/cheatsheet.ts

Created Mar 17, 2021
Embed
What would you like to do?
Advanced Typescript Cheatsheet
export type Await<T> = T extends PromiseLike<infer U> ? Await<U> : T;
export type IsPromise<T> = PromiseLike<infer U> ? true : false;
export type Length<T> = T extends { length: infer L } ? L : never;
export type KeysOfType<O, T> = {
[K in keyof O]: O[K] extends T ? K : never;
}[keyof O];
// ConvertLiterals would convert literal types like `1337` to their base type like `number` if set to true
export type PickByType<O, T, ConvertLiterals extends boolean = false> = {
[K in KeysOfType<O, T>]: ConvertLiterals extends true ? T : O[K]
};
export type OneOf<T, Strict extends boolean = true> = {
[OuterKey in keyof T]: Strict extends false
? { [K in OuterKey]: T[K] }
: { [InnerKey in OuterKey|keyof T]?: InnerKey extends OuterKey ? T[OuterKey] : never } & { [TheKey in OuterKey]: T[OuterKey] }
}[keyof T];
type Push<T extends unknown[], U> = T extends [...infer R] ? [...T, U] : never;
type PushFront<T extends unknown[], U> = T extends [...infer R] ? [U, ...T] : never;
type Pop<T extends unknown[]> = T extends [...infer R, infer U] ? U : never;
type PopFront<T extends unknown[]> = T extends [infer U, ...infer R] ? U : never;
type Shift<T extends unknown[]> = T extends [infer U, ...infer R] ? R : never;
type ShiftRight<T extends unknown[]> = T extends [...infer R, infer U] ? R : never;
type Reverse<T extends unknown[], U extends unknown[] = []> = Length<T> extends 1 ? Push<U, Pop<T>> : Reverse<ShiftRight<T>, Push<U, Pop<T>>>;
type Filter<T extends unknown[], U> = T extends [] ? [] : T extends [infer F, ...infer R] ? F extends U ? Filter<R, U> : [F, ...Filter<R, U>] : never
type TupleIncludes<T extends unknown[], U> = Length<Filter<T, U>> extends Length<T> ? false : true
type StringIncludes<S extends string, D extends string> = S extends `${infer T}${D}${infer U}` ? true : false;
type Includes<T extends unknown[]|string, U> = T extends unknown[] ? TupleIncludes<T, U> : T extends string ? U extends string ? StringIncludes<T, U> : never : never;
type Split<S extends string, D extends string> =
string extends S ? string[] :
S extends '' ? [] :
S extends `${infer T}${D}${infer U}` ? [T, ...Split<U, D>] : [S];
type Join<T extends unknown[], D extends string> = string[] extends T ? string : T extends string[]
? PopFront<T> extends string ? Length<T> extends 1 ? `${PopFront<T>}` : `${PopFront<T>}${D}${Join<Shift<T>, D>}` : never
: never;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment