typescript 是否可以将数量限制在某个范围内
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39494689/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to restrict number to a certain range
提问by ASDFGerte
Since typescript 2.0 RC (or even beta?) it is possible to use number literal types, as in type t = 1 | 2;
. Is it possible to restrict a type to a number range, e.g. 0-255, without writing out 256 numbers in the type?
从 typescript 2.0 RC(甚至是 beta 版?)开始,可以使用数字文字类型,如type t = 1 | 2;
. 是否可以将类型限制为一个数字范围,例如 0-255,而无需在类型中写出 256 个数字?
In my case, a library accepts color values for a palette from 0-255, and I'd prefer to only name a few but restrict it to 0-255:
就我而言,库接受调色板的颜色值从 0 到 255,我宁愿只列举几个,但将其限制为 0 到 255:
const enum paletteColor {
someColor = 25,
someOtherColor = 133
}
declare function libraryFunc(color: paletteColor | 0-255); //would need to use 0|1|2|...
采纳答案by AlexG
No it's not possible. That kind of precise type constraint is not available in typescript (yet?)
不,这是不可能的。这种精确的类型约束在打字稿中不可用(还没有?)
Only runtime checks/assertions can achieve that :(
只有运行时检查/断言才能实现:(
回答by Adam Szmyd
If You have small range, you can always write something like:
如果你的范围很小,你总是可以这样写:
type MyRange = 5|6|7|8|9|10
let myVar:MyRange = 4; // oops, error :)
Of course it works just for integers and is ugly as hell :)
当然,它只适用于整数,而且丑得要命:)
回答by Elie G.
It's not possible for the moment but there's an open issue on GitHub. Currently they are still waiting for a proposal but this functionality might come someday.
目前不可能,但GitHub 上有一个未解决的问题。目前他们仍在等待提案,但这一功能可能有一天会出现。
In short you won't be able to use a range of numbers as a type until a proposal comes out.
简而言之,在提案出来之前,您将无法使用一系列数字作为类型。
回答by Profesor08
Is it possible to restrict a type to a number range, e.g. 0-255, without writing out 256 numbers in the type?
是否可以将类型限制为一个数字范围,例如 0-255,而不在类型中写出 256 个数字?
Not posible until now, but you can make a lifehack, and generate desired sequence with one line of code and copy/paste result
直到现在不可能,但你可以做一个生活黑客,用一行代码和复制/粘贴结果生成所需的序列
new Array(256).fill(0).map((_, i) => i).join(" | ")
new Array(256).fill(0).map((_, i) => i).join(" | ")
回答by GibboK
Not using static type-checking, only at runtime for example using a library like io-tswhere you could use taggedUnion
for instance:
https://github.com/gcanti/io-ts/issues/313
不使用静态类型检查,仅在运行时使用例如io-ts 之类的库
,您可以在其中使用taggedUnion
例如:https:
//github.com/gcanti/io-ts/issues/313