有没有办法遍历TypeScript字符串文字的值?
type category = "foo" | "bar" | "baz" | "xyzzy"
for (c in category) {
// ... do something with each category
}
我目前有这样的事情:
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
}
但我宁愿使用类似
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")
}
使用typescript 2.1和keyof type,可以用另一种方式进行操作-您可以定义具有必要键的对象,并使用以下命令获取所有键的并集类型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' ]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句