来自this tutorial :用户定义的类型保护函数是返回“arg is aType”的函数。例如:
function isCustomer(partner: any): partner is Customer {
return partner instanceof Customer;
}
function signContract(partner: BusinessPartner): string {
let message: string;
if (isCustomer(partner)) {
message = partner.isCreditAllowed() ? 'Sign a new contract with the customer' : 'Credit issue';
} else {
message = partner.isInShortList() ? 'Sign a new contract with the supplier' : 'Need to evaluate further';
}
return message;
}
为什么“合作伙伴是客户”的返回类型比简单返回 bool 值更有优势?
最佳答案
线路
message = partner.isCreditAllowed() ? 'Sign a new contract with the customer' : 'Credit issue';
这是本教程的重点。
通常,在调用 isCreditAllowed
之前,您必须将 partner
转换为 Customer
。但由于 isCustomer
返回类型上有类型保护,TypeScript 可以省去强制转换的需要。
像 typeof A === B
这样的表达式隐式地带有这些保护。但是,通过用函数调用替换该条件,您必须通过在 isCustomer
的返回类型中进行声明,将该信息“放回”到表达式中。对于编译器来说,仅使用 boolean
是不够的。
关于Typescript:为什么/如何用户定义的 "Type Guard"的返回类型比返回 bool 值更好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72901753/