枚举TypeScript字符串文字

Ral*_*lph 8 typescript

有没有办法循环TypeScript字符串文字的值?

type category = "foo" | "bar" | "baz" | "xyzzy"

for (c in category) {
    // ... do something with each category
}
Run Code Online (Sandbox Code Playgroud)

我目前有这样的事情:

let cat: category = ...

switch (cat) {
    case "foo":
    default:
        process("foo")
        break

    case "bar":
        process("bar")
        break

    case "baz":
        process("baz")
        break

    case "xyzzy":
        process("xyzzy")
        break
}
Run Code Online (Sandbox Code Playgroud)

但我宁愿使用类似的东西

let others: category = []
for (c in category) {      // Iterate over possible category values
    if (c !== "foo") others.push(c)
}

if (others.indexOf(cat) >= 0) {
    process(cat)
} else {
    process("foo")
}
Run Code Online (Sandbox Code Playgroud)

art*_*tem 14

使用typescript 2.1和keyof类型,可以反过来做 - 您可以使用必要的键定义对象,并使用以下方法获取所有键的联合类型keyof:

let categoryKeys = {foo: '', bar: '', baz: '', xyzzy: ''}; // values do not matter

type category = keyof typeof categoryKeys;

let x: category = 'foo'; // ok
let z: category = 'z'; //  error TS2322: Type '"z"' is not assignable 
                       // to type '"foo" | "bar" | "baz" | "xyzzy"'.

console.log(Object.keys(categoryKeys)); // prints [ 'foo', 'bar', 'baz', 'xyzzy' ]
Run Code Online (Sandbox Code Playgroud)