2016-09-14 147 views
10

既然typescript 2.0 RC(甚至是beta?)可以使用数字文字类型,如type t = 1 | 2;。是否可以将类型限制在数字范围内,例如0-255,没有写出256个数字的类型?是否可以将数字限制在一定范围内

在我的情况,出库接受的颜色值从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|... 
+1

注:枚举定义一组名为** numeric **常量,而不是新类型。因此,声明可以传递数字而不是'paletteColor's是不必要的。 –

+1

@Burt_Harris true。还需要一种将枚举限制为0-255的方法。人们也可以使用索引器对象而不是枚举,虽然有点难看。无论哪种方式都不需要'|',如果它被限制在0-255或0-255之间,它应该在最好的情况下简单地称为“paletteColor”。 – ASDFGerte

+1

注意:从TS 2.4起,现在允许字符串文字作为枚举值https://blogs.msdn.microsoft.com/typescript/2017/06/27/announcing-typescript-2-4/#string-enums –

回答

5

不,这不可能。那种精确的类型约束不打字稿用(没有?)

只有运行时检查/断言可以做到这一点:(

15

如果您有很小的范围内,你总是可以写类似:

type MyRange = 5|6|7|8|9|10 

let myVar:MyRange = 4; // oops, error :) 

当然,它只适用于整数,并且很糟糕:)

+0

https ://stackoverflow.com/questions/39494689/is-it-possible-to-restrict-number-to-a-certain-range#comment79287008_39494689 –

相关问题