将数字类型转换为对应的字符串一

时间:2019-10-25 17:44:17

标签: typescript generics

例如,我有一些带有具体数字的类型

type Num = 42;

现在我要使转换成为通用

type NumberToString<N> = ... // N as string instead of number

如此

type A = NumberToString<Num>; // "42"
type B = NumberToString<1>;   // "1"

我怎么写这样的转换器?

1 个答案:

答案 0 :(得分:2)

我认为这对于任意数字都是不可能的。表面上有一个open issue专门用于在类型系统中进行数学运算,但据我所知,在那里没有发生太多事情。

如果您可以将其限制为“合理”范围内的非负整数,则可以在某处声明一个巨大的元组,并按如下所示进行操作:

type HugeTuple = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0]; // as long as you need
type NumToStr<N extends number> = { [K in keyof HugeTuple]: K }[N];

type One = NumToStr<1>; // "1"
type TwoOrFortyTwo = NumToStr<2 | 42> // "2" | "42"

所以,呃,你去了。祝你好运!

Link to code