Created
February 22, 2023 21:54
-
-
Save WoLfulus/fbdbf370792cebbefbd98f1074e8cc51 to your computer and use it in GitHub Desktop.
"Switch Case" for TypeScript Types
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
// PoC, has problems with type matching in case array | |
type Case<V extends boolean = any, T = any> = [V, T]; | |
type Switch<T extends readonly any[], Fallback = never> = | |
T extends [infer Head, ...infer Rest] ? [Head] extends [[true, infer V]] ? V : | |
Switch<Rest> : Fallback; | |
type Default<V> = [true, V]; | |
type Extends<T, U> = T extends U ? true : false; | |
type NumberToString<N> = Switch< | |
[ | |
Case<Extends<N, 1>, "one">, | |
Case<Extends<N, 2>, "two">, | |
Case<Extends<N, 3>, "three">, | |
Case<Extends<N, 4>, "four">, | |
Default<"something else"> | |
] | |
>; | |
type One = NumberToString<1>; | |
// ^? | |
type Two = NumberToString<2>; | |
// ^? | |
type Three = NumberToString<3>; | |
// ^? | |
type Four = NumberToString<4>; | |
// ^? | |
type Five = NumberToString<5>; | |
// ^? | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
:(