Skip to content

Instantly share code, notes, and snippets.

@tlkahn
Created July 14, 2024 03:46
Show Gist options
  • Save tlkahn/f0c1fce9da479433279331d35d87b48c to your computer and use it in GitHub Desktop.
Save tlkahn/f0c1fce9da479433279331d35d87b48c to your computer and use it in GitHub Desktop.
a koan collection for typescript
// Literal type
type Drinks = 'Coke' | 'Milk' | 'Water' | 'Coffee';
type UnUnite<T, K> = T extends K ? never : T;
type Result = UnUnite<string | number | boolean, string>; // Result: number | boolean
type HealthDrinks = UnUnite<Drinks, 'Coke'>;
// `infer`
// "destructuring type". "Pattern matching"
type Flip<T> = T extends [infer A, infer B] ? [B, A] : T;
type _1 = Flip<[number, boolean]>;
type Args<T> = T extends (...a: infer A) => infer R ? A : never;
type UnionFromTuple<T> = T extends [...a: infer A] ? A : T;
type uft = UnionFromTuple<['hello', 'world']>;
type Xs1 = Args<typeof Math.pow>;
type Xs2 = Args<typeof document.getElementById>;
type Head<T> = T extends [infer H, ...infer _] ? H : never;
type Rest<T> = T extends [infer _, ...infer Rest /* or ...a: infer Rest */]
? Rest
: never;
type Rest2<T> = T extends [infer _, ...a: infer R] ? R : never;
type One = Head<[1, 2, 3]>;
type AfterOne = Rest<[1, 2, 3]>;
type NewAfterOne = Rest2<[1, 2, 3]>;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment