Skip to content

Instantly share code, notes, and snippets.

@mauroc8
Last active January 12, 2024 18:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mauroc8/9a8577d87e5a4f47431ebfebfc494b6a to your computer and use it in GitHub Desktop.
Save mauroc8/9a8577d87e5a4f47431ebfebfc494b6a to your computer and use it in GitHub Desktop.
Pattern matching in typescript example
type LinkedList<A> = {} | { head: A; tail: LinkedList<A> };
type ToUnion<T> = T extends { head: infer N; tail: infer Tail }
? N | ToUnion<Tail>
: never;
type ToArray<T> = T extends { head: infer N; tail: infer Tail }
? [N, ...ToArray<Tail>]
: [];
type myList = { head: 1; tail: { head: 4; tail: { head: 2; tail: {} } } };
type foo = ToUnion<myList>; // 1 | 4 | 2
type bar = ToArray<myList>; // [1, 4, 2]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment