打字稿:为什么不严格返回类型?

时间:2020-07-21 02:32:04

标签: typescript

有一个小片段,返回类型错误的函数返回没有错误。

type Human = {
  head: number
  body: number
}

const human: Human = {
  head: 1,
  body: 1,
}

const humanFn: (human: Human) => Human = (human) => {
  return {
    // ...human, 
    head: human.head,
    body: human.body,
    tail: 1, // allows illegal props
  }
}

humanFn({
  ...human,
  tail: 1, // here is and error
})

所以问题是为什么TS允许添加附加道具来返回对象tail: 1, // allows illegal props?有办法避免吗?

UPD:

所以实际上我发现了存在的TS问题https://github.com/microsoft/TypeScript/issues/241

和“解决方法”将返回对象包装在R.identity<Human>(...)之类的东西中(来自ramda)

1 个答案:

答案 0 :(得分:1)

您的代码不会引发编译错误,
但是以下代码会引发编译错误。

function humanFn(human: Human): Human {
  return {
    // ...human, 
    head: human.head,
    body: human.body,
    tail: 1, // Error
  }
}

以下内容也会引发编译错误

const humanFn: (human: Human) => Human = (human): Human => {
  return {
    // ...human, 
    head: human.head,
    body: human.body,
    tail: 1, // Error
  }
}

您的问题似乎是this question的另一种情况。

最后,我在GitHub上找到了the issue,正是关于这个问题。在 简短:

理想情况下,这将是一个错误。不幸的是事实证明这非常 很难解决这个问题,而不会在 失控的递归和/或性能