javascript - TypeScript Convert string union type to number union type - Stack Overflow

Is it possible to convert string union type to number union type in TypeScript?e.g. Given a union type

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.

Share Improve this question edited Aug 27, 2021 at 9:40 T.J. Crowder 1.1m200 gold badges2k silver badges2k bronze badges asked Aug 27, 2021 at 8:14 loveyunkloveyunk 3783 silver badges13 bronze badges 1
  • 1 Same question but without answer stackoverflow./questions/65410801/… – captain-yossarian from Ukraine Commented Aug 27, 2021 at 8:45
Add a ment  | 

2 Answers 2

Reset to default 6

This 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条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信