Convert a string constant to a numeric constant statically, aka in a type expression

Viewed 12

I want to write a type that converts a string to an integer as part of a type alias, aka at compile time:

type strToNum<T extends string> = +T; // Invalid
type theAnswer = strToNum<'42'>; // theAnswer is a numeric type that only takes 42

Obviously you can do this for specific strings:

type strToNum<T extends string> = T extends '1' ? 1 : T extends '2' ? 2 : never;
type a = strToNum<'2'>;

but that doesn't help with the general case.

0 Answers
Related