TypeScript在将必需类型设置为可选字段时不会引发错误。

huangapple go评论121阅读模式
英文:

Typescript does not throw error when required type gets set with optional field

问题

我有这段代码:

let bank_account = await createBankAccount({
    acc_number: 'AT' + group.id,
    allow_out_payment: true,
    bank_id: bank.data[0],
    partner_id: group.odoo_id,
})

我的问题是partner_id的类型是数字,而group.odoo_id是可选的。

TypeScript没有标记这个为类型错误。group.odoo_id可能是未定义的,但TypeScript没有任何反应。有什么问题吗?

英文:

I have this code piece:

  let bank_account = await createBankAccount({
      acc_number: 'AT' + group.id,
      allow_out_payment: true,
      bank_id: bank.data[0],
      partner_id: group.odoo_id,
   })

My problem here is that partner_id is of type number and group.odoo_id is optional

TypeScript在将必需类型设置为可选字段时不会引发错误。

TypeScript在将必需类型设置为可选字段时不会引发错误。

Typescript does not mark this as an type error. group.odoo_idcould be undefined but typescript does nothing. Whats wrong here?

答案1

得分: 0

如果你想让TypeScript在这些情况下抛出错误,你需要在tsconfig.json中将选项strictNullChecks设置为true

然后,如果你确信当前的值已定义,你必须这样标记它:

partner_id: group.odoo_id!,
英文:

If you want TypeScript to throw an error in those cases, you need to set the option strictNullChecks to true in the tsconfig.json.

Then, if you're sure that the current value is defined, you have to mark it like that:

partner_id: group.odoo_id!,

huangapple
  • 本文由 发表于 2023年5月11日 19:47:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76227309.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定