Typescript从元组/数字数组派生联合类型

时间:2020-10-01 20:47:06

标签: javascript typescript

Typescript derive union type from tuple/array values

非常有用。

const list = ['a', 'b', 'c'] as const; // TS3.4 syntax
type NeededUnionType = typeof list[number]; // 'a'|'b'|'c';

现在,我尝试制作一种具有以下特征的整数 范围(0 ... 255)。

对于初始测试,手动准备[0,1,2,3]后,它会按预期工作。

  const int3 = [0, 1, 2, 3] as const;
  type Int3 = typeof int3[number];
  //  0 | 1 | 2 | 3
  const a: Int3 = 3; //ok, but error on >=4

但是,当[0,1,..,255]与Array.keys()迭代进行预配对时,它将无法工作...

  const int255 = [...Array(255).keys()] as const; // [0,1,..,255]
  type Int255 = typeof int255[number];
  const colorCode: Int255 = 300; //ok to compile,should be error

对此有任何解决方法吗?谢谢。

此处的相关主题:

Is it possible to restrict number to a certain range

没有回答这个问题,它是TypeScript2.0年龄(超过5年)

2 个答案:

答案 0 :(得分:2)

总结评论中的冗长讨论:在撰写本文时,(实际上)除非您明确列出所有数字,否则这是不可能的。即便如此,它还是相当有限的。

但是,对此有一个开放功能请求,可以在这里找到:https://github.com/microsoft/TypeScript/issues/15480

答案 1 :(得分:-1)

对此有任何解决办法吗?

不,暂时不。

相关问题