我有一个简单的类型:
type person = 'man' | 'woman'
并且我具有输入字符串CCD_ 1。
如何检查它是否是person
?
由于TypeScript类型只是一个编译时构造,因此没有内置的方法来检查x
是否为person
。然而,您可以编写自己的类型窄化函数,该函数可以执行等效操作:
function isPerson(x: string): x is person {
return x == 'man' || x == 'woman'
}
使用此功能时,TypeScript会自动缩小您的类型,例如:
function funcThatTakesAPerson(p: person) {
//...
}
function funcThatTakesAString(x: string) {
funcThatTakesAPerson(x); // compile error; x is a string, not a person
if (isPerson(x)) {
funcThatTakesAPerson(x); // works; TypeScript knows that x is a person
}
}