gpt4 book ai didi

typescript - 为什么 typescript 中的方法参数不是逆变的

转载 作者:搜寻专家 更新时间:2023-10-30 21:32:40 26 4
gpt4 key购买 nike

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

最佳答案

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

有一个选项 (strictFunctionTypes) 可以使不是源自方法的函数签名的参数行为逆变,但方法明确免于更严格的检查。来自PR为函数引入这种更严格的模式,我们了解了方法豁免背后的原因:

Methods are excluded specifically to ensure generic classes and interfaces (such as Array) continue to mostly relate covariantly. The impact of strictly checking methods would be a much bigger breaking change as a large number of generic types would become invariant (even so, we may continue to explore this stricter mode).

关于typescript - 为什么 typescript 中的方法参数不是逆变的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57074102/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com