function isEnumValue(s: string): s is keyof typeof Items {
return s in Items && typeof Items[s as any] === 'number';
}
console.log(isEnumValue('One')); // true
console.log(isEnumValue('1')); // false
enum Items {
One = 1,
Two,
}
const a1: keyof typeof Items = "One" // OK
const a2: keyof typeof Items = 1 // not OK
const b1: keyof typeof Items = "Two" // OK
const b2: keyof typeof Items = 2 // not OK
// Reduce typing whole "keyof typeof Items"
type Valid = keyof typeof Items
const c1: Valid = "One" // OK
const c2: Valid = 1 // not OK
enum Items {
One = 1,
Two,
}
const a1: keyof typeof Items = "One" // OK
const a2: keyof typeof Items = 1 // not OK
const b1: keyof typeof Items = "Two" // OK
const b2: keyof typeof Items ...
Playground链接
Type '1' is not assignable to type '"One" | "Two"'.
Type '2' is not assignable to type '"One" | "Two"'.
Type '1' is not assignable to type '"One" | "Two"'.
2条答案
按热度按时间nxagd54h1#
EnumsMap到JavaScript中的对象,因此您可以执行以下操作:
这里有一个潜在的边缘情况,因为数字枚举也会自动得到一个反向Map,将一个数字枚举值的字符串表示传递给上面的函数,也会使函数返回
true
:如果需要,可以通过另外确保密钥查找返回一个数值来解决此问题:
2sbarzqh2#
对于静态类型检查,请使用:
Playground链接