将数字类型转换为对应的字符串一 [英] Convert number type to corresponding string one
本文介绍了将数字类型转换为对应的字符串一的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,我有一些带有具体数字的类型
I have some type with concrete number, for example
type Num = 42;
现在我要使转换成为通用
Now I want to make converting generic
type NumberToString<N> = ... // N as string instead of number
如此
type A = NumberToString<Num>; // "42"
type B = NumberToString<1>; // "1"
我怎么写这样的转换器?
How can I write such converter?
推荐答案
我认为任意数字都不可行.有一个未解决的问题表面上致力于在类型系统中进行数学运算,但没什么大不了的据我所知发生在那里.
I don't think that's possible for arbitrary numbers. There's an open issue ostensibly dedicated to doing math in the type system, but nothing much is happening there as far as I can see.
如果您可以将其限制为在合理"范围内的非负整数,则可以在某处声明一个巨大的元组,并按如下所示进行操作:
If you're okay limiting it to non-negative whole numbers in a "reasonable" range, you can declare a huge tuple somewhere and do it like this:
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"
所以,呃,你去了.祝你好运!
So, uh, there you go. Good luck!
这篇关于将数字类型转换为对应的字符串一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文