'TypeScript Template Literal Type - how to infer numeric type?
// from a library
type T = null | "auto" | "text0" | "text1" | "text2" | "text3" | "text4";
//in my code
type N = Extract<T, `text${number}`> extends `text${infer R}` ? R : never
For the above piece of code N will be equivalent to "0" | "1" | "2" | "3" | "4". How can I convert that to a numeric type, i.e. 0 | 1 | 2 | 3 | 4?
Have already tried putting & number in some places, like infer R & number, but none of that works.
Solution 1:[1]
Thanks for the answer, @captain-yossarian. I found you can also keep the tuple of Mapped<MAXIMUM_ALLOWED_BOUNDARY> and index using string index. Of course, Range must be a tuple.
type MAXIMUM_ALLOWED_BOUNDARY = 999
type Mapped<
N extends number,
Result extends Array<unknown> = [],
> =
(Result['length'] extends N
? Result
: Mapped<N, [...Result, Result['length']]>
)
type NumberRange = Mapped<MAXIMUM_ALLOWED_BOUNDARY>; // <- tuple [0, 1, 2, 3, ...]
type ConvertToNumber<T extends string, Range extends number[]> =
T extends keyof Range ? Range[T] : never;
type _ = ConvertToNumber<'5', NumberRange> // 5
type __ = ConvertToNumber<'125', NumberRange> // 125
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Trevor Manz |
