本文介绍了是否可以将数量限制在某个范围内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
从 typescript 2.0 RC(甚至是 beta 版?)开始,可以使用数字文字类型,如 type t = 1 |2;
.是否可以将类型限制为数字范围,例如0-255,没有在类型中写出256个数字?
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?
就我而言,库接受调色板的颜色值从 0 到 255,我更愿意只列举几个但将其限制为 0-255:
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:
const enum paletteColor {
someColor = 25,
someOtherColor = 133
}
declare function libraryFunc(color: paletteColor | 0-255); //would need to use 0|1|2|...
推荐答案
不,这不可能.打字稿中没有这种精确的类型约束(还没有?)
No it's not possible. That kind of precise type constraint is not available in typescript (yet?)
只有运行时检查/断言才能做到这一点:(
Only runtime checks/assertions can achieve that :(
这篇关于是否可以将数量限制在某个范围内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!