Skip to content

Instantly share code, notes, and snippets.

@WoLfulus
Created February 22, 2023 21:54
Show Gist options
  • Save WoLfulus/fbdbf370792cebbefbd98f1074e8cc51 to your computer and use it in GitHub Desktop.
Save WoLfulus/fbdbf370792cebbefbd98f1074e8cc51 to your computer and use it in GitHub Desktop.
"Switch Case" for TypeScript Types
// 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>;
// ^?
@Brayan-724
Copy link

:(

@WoLfulus
Copy link
Author

:(

🤔

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment