在Typescript中,您可以在派生类中使用协变方法参数。
看起来像是对LSP的公然违反。
这部分语言设计的目的是故意还是设计限制?
interface A {
a: number;
}
interface B extends A {
b: number;
}
class Base {
public foo(arg0: A): B {
return { a: 0, b: 42 };
}
}
class Derived extends Base {
public foo(arg0: B): B { // covariant parameter is allowed, not OK
return { a: +arg0.a.toPrecision(2), b: +arg0.b.toPrecision(2) }; // runtime error, b is undefined, although should have been required
}
}
let b: Base = new Derived(); // Assign a sub class to a base class should always be ok
b.foo({ a: 10}); // no need to pass in b, right ?