-
-
Save mauroc8/9a8577d87e5a4f47431ebfebfc494b6a to your computer and use it in GitHub Desktop.
Pattern matching in typescript example
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
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