常识表明,子类型在返回类型方面应该是协变的,但在参数类型方面应该是逆变的.因此,应该拒绝以下内容,因为严格协变的参数类型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 …Run Code Online (Sandbox Code Playgroud) 我希望以下代码无法转换,因为B不应该是array.push的有效类型.我错过了什么?
class A {};
class B {};
const arr: A[] = [];
arr.push(new B());
Run Code Online (Sandbox Code Playgroud)