Typescript:为什么/如何用户定义的 "Type Guard"的返回类型比返回 bool 值更好?

标签 typescript typeguards

来自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/

相关文章:

node.js - 如何使用 npm 命令编译 typescript ?

typescript - 如何通过 bool 值输入保护?

python - 无法从 'TypeGuard' 导入名称 'typing_extensions'

javascript - 为什么分配给变量(别名条件)时对类属性的类型缩小检查不起作用?

javascript - Angular 使用 html 文件的模板路径

javascript - 在 Typescript 中使用 Object.keys 时避免隐式 'any' 类型

javascript - 无法实现 ValidatorFn 接口(interface)

typescript - Typeguard 不会缩小类型

javascript - 确定在 typescript 中可能具有多种类型的参数类型

typescript 模块 : defined is not defined