You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript未检测必填类型赋值可选字段的错误问题

为什么TypeScript没检测到partner_id的类型不匹配?

以下是几种常见的原因:

  • createBankAccount的参数类型其实允许partner_id为undefined
    你可能误以为partner_id的类型是纯number,但实际定义createBankAccount的入参时,partner_id可能被设为可选(加了?)或者类型是number | undefined。比如类型定义可能是这样:

    interface CreateBankAccountParams {
      acc_number: string;
      allow_out_payment: boolean;
      bank_id: any;
      partner_id?: number;
    }
    

    这种情况传undefined完全合法,TS不会报错。

  • 没开启严格空值检查
    如果你的tsconfig.json里没启用strictNullChecks(或者包含它的strict模式),TypeScript会默认把undefined和null当成能赋值给任意类型的值,这时候把可能为undefined的group.odoo_id传给number类型的partner_id,自然不会触发错误。

  • group.odoo_id的类型被提前缩小了
    在这段代码之前,你可能做过条件判断(比如if (group.odoo_id) { ... })或者用了类型断言(比如group.odoo_id as number),TypeScript会认为此时group.odoo_id不可能是undefined,所以不会提示类型错误。

  • createBankAccount的参数类型是any
    如果createBankAccount的入参被定义成any类型,TypeScript会直接跳过所有类型校验,不管你传什么值都不会报错。

内容的提问来源于stack exchange,提问作者Ilijanovic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 15:54:53