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)的Integer类型。
对于初始测试,当手动准备[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但是,当使用Array.keys()迭代准备[0,1,..,255]时,它将无法工作...
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年前)
发布于 2020-10-02 05:28:12
在评论中总结一段冗长的讨论:在撰写本文时,除非您显式地写出所有单独的数字,否则(实际上)这是不可能的。即使这样,它也是相当有限的。
然而,有一个开放的功能请求,可以在这里找到:https://github.com/microsoft/TypeScript/issues/15480
发布于 2020-10-02 06:01:16
有没有解决这个问题的办法?
不,现在不是。
https://stackoverflow.com/questions/64162970
复制相似问题