简体   繁体   English

申报单是否会影响TypeScript类型扣除?

[英]Should the declaration order affect TypeScript type deduction?

It seems that TypeScript's translator somehow relies on the order of declaration, at least in case of overloaded functions.似乎 TypeScript 的翻译器在某种程度上依赖于声明的顺序,至少在重载函数的情况下。

Lets say we have classes for 2- and 3-dimensional vectors:假设我们有 2 维和 3 维向量的类:

class Vector2 {
  public get x() : number
  public get y() : number
}
class Vector3 {
  public get x() : number
  public get y() : number
  public get z() : number
}

And we have an overloaded function which accepts either Vector2 or Vector3 :我们有一个重载的 function 接受Vector2Vector3

function add(a : Vector2, b : number) : Vector2;
function add(a : Vector3, b : number) : Vector3;

Depending on which signature of add() goes first - with Vector2 or Vector3 result - the compiler may deduce different type of the result, even if we pass as a parameter exactly Vector3 .根据add()的哪个签名首先出现 - 使用Vector2Vector3结果 - 编译器可能会推断出不同类型的结果,即使我们将Vector3作为参数传递也是如此。 For instance, in case of the same order as mentioned above, the following code:例如,在与上述相同的顺序的情况下,以下代码:

const r = add(new Vector3, 5)

Will return Vector2 instead of Vector3 .将返回Vector2而不是Vector3 Because of this, if we put constraints on the possible type of r as Vector3 :因此,如果我们将r的可能类型限制为Vector3

const r : Vector3 = add(new Vector3, 5)

the code will not compile.代码不会编译。

Is this should to be so?应该是这样吗? Because for me it looks like an error in the translator.因为对我来说,这看起来像是翻译器的错误。

This is the expected behaviour of Typescript: when you call an overloaded function, the compiler chooses the first overload signature which is compatible at the call-site, not the most-specific signature.这是 Typescript 的预期行为:当您调用重载的 function 时,编译器会选择在调用点兼容的第一个重载签名,而不是最具体的签名。 From the docs :文档

TypeScript chooses the first matching overload when resolving function calls. TypeScript 在解析 function 调用时选择第一个匹配的重载 When an earlier overload is “more general” than a later one, the later one is effectively hidden and cannot be called.当早期的重载比后面的“更通用”时,后面的重载被有效地隐藏并且不能被调用。

Since your Vector3 is a structural subtype of your Vector2 , the Vector3 overload signature is more specific so you should write that one before the Vector2 overload signature.由于您的Vector3Vector2结构子类型,因此Vector3重载签名更具体,因此您应该在Vector2重载签名之前编写该签名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM