【发布时间】:2021-02-11 19:31:20
【问题描述】:
我很难理解为什么以下内容不会引发错误
type Callback<T> = () => T
function format<V>(callback: Callback<V>): V {
return callback()
}
type Test = {foo: string}
format<Test>(() => {
return {
foo: 'hello',
bar: 'dd' // I expect an error to be here as `bar` does not exist on type Test
}
})
// if I explicitly set the return type in the callback then I get the correct error
format<Test>((): Test => {
return {
foo: 'hello',
bar: 'dd' // this now errors as I have set the return type.
}
})
我不禁觉得这是重复?
这是typescript 的限制并且“符合预期”,还是我的types 不正确?
【问题讨论】:
-
有什么问题?如果您认为这是错误的,我会在 GitHub 页面上针对 typescript 提出问题。 为什么下面没有抛出错误因为打字稿转译器没有
¯\_(ツ)_/¯ -
为什么
format中的回调函数需要显式设置返回类型才能显示错误,为什么第一种情况没有显示错误?当format函数清楚地表明返回类型是什么时,OP 感觉不需要输入两次Test(后一种情况)。 -
@Liam 嘿-是的,我已经澄清了我的问题-这是预期的
typescript限制。
标签: typescript typescript-generics