Is it possible to convert string union type to number union type in TypeScript?
e.g. Given a union type A:
type A = '7' | '8' | '9'
Convert to:
type B = 7 | 8 | 9
The numbers in A
can be any number, not just digits or integers.
Is it possible to convert string union type to number union type in TypeScript?
e.g. Given a union type A:
type A = '7' | '8' | '9'
Convert to:
type B = 7 | 8 | 9
The numbers in A
can be any number, not just digits or integers.
- 1 Same question but without answer stackoverflow./questions/65410801/… – captain-yossarian from Ukraine Commented Aug 27, 2021 at 8:45
2 Answers
Reset to default 6This is now possible (as of typescript 4.8.4), using type inference:
type ToNumber<S> = S extends `${infer N extends number}` ? N : never
type A = "7" | "8" | "9" | "0.11" | "1.52"
type B = ToNumber<A>
This unfortunately cannot handle any other number formats, even in 5.2.0-beta (so 1.2e3
, 0xff4
, 0b1110
are off the table).
Playground Here
Going from string
to number is not possible, as far as I know. However, how about the other way around, would that work for you? You can do this by using template literals:
type B = 7 | 8 | 9;
type A = `${B}`;
Playground Link
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745319272a4622366.html
评论列表(0条)