常识表明子类型应该在返回类型方面是协变的,但在参数类型方面应该是逆变的。因此,由于 的严格协变参数类型,应拒绝以下内容E.f
:
interface C {
f (o: C): void
}
interface D extends C {
g (): void // give D an extra service
}
class E implements C {
// implement f with a version which makes stronger assumptions
f (o: D): void {
o.g() // rely on the extra service promised by D
}
}
// E doesn't provide the service required, but E.f will accept
// an E argument as long as I invoke it via C.
var c: C = new E()
console.log('Try this: ' + c.f(c))
确实,运行程序会打印
Uncaught TypeError: o.g is not a function
所以:(1)这里的理由是什么(大概有一个,但是不令人满意和JavaScripty);(2) 编译器在这种情况下不能忽略警告是否有任何实际原因?