typescript 验证字符串是否为枚举值

rbl8hiat  于 2023-02-20  发布在  TypeScript
关注(0)|答案(2)|浏览(212)

我有一个打字机脚本enum

enum Items {
  One = 1,
  Two,
}

如何知道strings是否是Items的有效字符串表示?例如,'One'是有效的,但'1'不是。

nxagd54h

nxagd54h1#

EnumsMap到JavaScript中的对象,因此您可以执行以下操作:

enum Items {
  One = 1,
  Two,
}

function isEnumValue(s: string): s is keyof typeof Items {
    return s in Items;
}

这里有一个潜在的边缘情况,因为数字枚举也会自动得到一个反向Map,将一个数字枚举值的字符串表示传递给上面的函数,也会使函数返回true

console.log(isEnumValue('1')); // true

如果需要,可以通过另外确保密钥查找返回一个数值来解决此问题:

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
2sbarzqh

2sbarzqh2#

对于静态类型检查,请使用:

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"'.

相关问题