Skip to content

Instantly share code, notes, and snippets.

@madflanderz
Last active November 26, 2020 08:08
Show Gist options
  • Save madflanderz/309bd84351f89d9afaf7669c202dbb0a to your computer and use it in GitHub Desktop.
Save madflanderz/309bd84351f89d9afaf7669c202dbb0a to your computer and use it in GitHub Desktop.
// type Todo = {id: string, title: string}
// MyPick<Todo, 'title'>
type MyPick<T, K extends keyof T> = {
[S in K]: T[S]
}
// type R = MyReadonly<{id: string}>
type MyReadonly<T> = {
readonly [S in keyof T]: T[S]
}
// const tuple = ['tesla', 'model 3', 'model X', 'model Y'] as const
// TupleToObject<typeof tuple>
// creates this type: { tesla: 'tesla'; 'model 3': 'model 3'; 'model X': 'model X'; 'model Y': 'model Y'}
type TupleToObject<T extends readonly any[]> = {
[k in T[number]]: k
}
// First<[3, 2, 1]>. -> 3
// First<[() => 123, { a: string }] --> () => 123
type First<T extends any[]> = T extends [] ? never : T[0]
// const tesla = ['tesla', 'model 3', 'model X', 'model Y'] as const
// Length<typeof tesla>
type Length<T extends readonly string[]> = T['length']
// MyExclude<"a" | "b" | "c", "a"
type MyExclude<T, U> = T extends U ? never: T;
// Awaited<Promise<string>> returns string
type Awaited<T> = T extends Promise<infer R> ? R : never;
// If<true, 'a', 'b'> --> 'a'
// If<false, 'a', 'b'> --> 'b'
type If<C extends Boolean, T, F> = C extends true ? T : F
// MyReturnType<() => ComplexObject> --> ComplexObject
type MyReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : never;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment