我不明白为什么下面的代码没有报错
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
不正确?
format
中的回调函数需要显式设置返回类型才能显示错误,而第一个情况却没有显示错误?OP觉得当format
函数明确指示返回类型时,不应该需要两次输入Test
(后一种情况)。 - Nishanttypescript
限制吗? - amwill04