【问题标题】:TypeScript is not capturing errors when adding wrong keys to objects [duplicate]向对象添加错误键时,TypeScript 未捕获错误 [重复]
【发布时间】:2021-04-14 10:23:24
【问题描述】:

我的Person 类型定义如下,

interface IPerson {
  name: string;
  age: number
}

另外,我正在为所有方法创建一个通用类型,

type IPersonMethod = (
  person: IPerson,
  newAge: number
) => IPerson;

我的假设是每当我使用这种类型创建一个新方法时,如下所示,

const updateAge: IPersonMethod = (person, newAge) => {
  return {
    ...person,
    age: newAge,
  }
}

它只接受IPerson 类型的personnumber 类型的age 并且将始终返回IPerson 类型的对象,因此上述工作正常,没有任何故障。

但是如果我添加了任何错误的键(假设我错误地输入了ag 而不是age),为什么它不会抛出任何错误? (下面的效果也很好,这不是我所期望的)

const updateAge: IPersonMethod = (person, newAge) => {
  return {
    ...person,
    ag: newAge,
  }
}

【问题讨论】:

标签: reactjs typescript redux


【解决方案1】:

发生这种情况是因为 ...person 已经具有字段 age,因此您实际上返回的类型 IPerson 带有额外的错误字段 ag。 Typescript 不支持限制该额外属性。

【讨论】:

  • 我最担心的是,这是捕获错误,如果我再次向该方法添加返回,它会正确抛出错误,我的意思是这很好用const updateAge: IPersonMethod = (person, newAge): IPerson => {
  • @MaranSowthri 然后在函数括号 (person, newAge): IPerson => 后面添加 IPerson。您将强制 ts 检查返回对象的类型。
  • 正确,(这就是我所做的)但我为什么要这样做两次是个问题。
猜你喜欢
  • 2018-08-02
  • 1970-01-01
  • 2018-01-06
  • 2017-08-26
  • 2019-02-27
  • 1970-01-01
  • 1970-01-01
  • 2014-08-28
  • 1970-01-01
相关资源
最近更新 更多