在下面的示例中,Promise::then
访问者函数f
有望收到Example
。如果我显式传递一个缺少属性的格式错误的对象,我会得到一个类型错误。为什么没有在打字稿中检查头等功能?
但如果我只是传递函数f
到.then(f)
我没有得到任何类型的错误,即使打字稿知道在Promise<T>
的T
的类型不是Example
。
interface Example {
id: number
age: number
}
interface Promise <T> {
then <U> (f: (a: T) => U) : Promise<U>
}
function f(s:Example){
return s.age
}
var p : Promise<{ id: number }>
p.then(f) // no type error (bad)
p.then(function(a){
f(a) // type error (good)
})
我想知道为什么会发生这种情况,但也有技术来缓解Typescript中的宽容类型检查。
如果双变量解释了这种现象,那么当明确应用f
时为什么会出现类型错误?为什么他们的第一类函数与显式应用程序有不同的规则?
可能的重复:http://stackoverflow.com/questions/38699449/compatible-types-in-functions/38700451#38700451。另请参见[类型检查不稳定性:在TypeScript团队/社区中标准化处理此类问题](https://github.com/Microsoft/TypeScript/issues/9825) – artem
@artem我不认为这是由于双变量。但我可能是错的。 –