为什么方法参数在打字稿中不矛盾

时间:2019-07-17 10:47:17

标签: typescript

在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 ?

1 个答案:

答案 0 :(得分:2)

方法参数在打字稿中表现为双变量。有一个proposal使它们的行为相反,但是由于自2016年以来一直开放,因此可能不是优先事项。

有一个选项(strictFunctionTypes)使不是源自方法的函数签名的参数起反作用,但方法明确地免于更严格的检查。通过PR引入了针对函数的更严格的模式,我们对方法豁免背后的原因有了一个认识:

  

专门排除方法以确保通用类和接口(例如Array)继续主要是协变关系。严格检查方法的影响将是一个重大突破,因为大量泛型类型将变为不变(即使如此,我们可能会继续探索这种更严格的模式)。