【发布时间】:2019-02-21 23:06:27
【问题描述】:
使用打字稿 3.0+。请参阅以下涉及泛型类型变量的简单设置:
abstract class BaseClass {
public abstract merge<T>(model?: T): T;
}
class MyClass extends BaseClass {
public Value: string;
public merge<MyClass>(model?: MyClass): MyClass {
this.Value += model.Value; // <--Property 'Value' does not exist on type 'MyClass'
return this; // <--Type 'this' is not assignable to type 'MyClass'.
// Type 'MyClass' is not assignable to type 'MyClass'.
// Two different types with this name exist, but they are unrelated.
}
}
我注意到 Typescript 编译器描述的错误,但这些错误对我来说没有意义。为什么这是错误的?
更新
我现在明白,MyClass 中合并方法上方的原始代码定义了一个与“MyClass”同名的新泛型类型变量,这解释了错误。所以我做出如下所示的改变。这仍然会产生错误,我在merge方法上方对此进行了评论:
abstract class BaseClass {
public abstract merge<T>(model?: T): T;
}
class MyClass extends BaseClass {
public Value: string;
/*
Property 'merge' in type 'MyClass' is not assignable to the same property in base type 'BaseClass'.
Type '(model?: MyClass) => MyClass' is not assignable to type '<T>(model?: T) => T'.
Types of parameters 'model' and 'model' are incompatible.
Type 'T' is not assignable to type 'MyClass'.
*/
public merge(model?: MyClass): MyClass {
this.Value += model.Value;
return this;
}
}
为什么我不能在这里使用 MyClass 作为变量类型?事实上,我似乎无法用任何其他可以使其工作的类型(例如字符串、数字、另一个类)来替换它。
即使我尝试将 T 定义为扩展 BaseClass 的类型:
abstract class BaseClass {
public abstract merge<T extends BaseClass>(model?: T): T;
}
这仍然会在 MyClass 中产生相同的错误。请注意,这适用于 TypeScript 2.2.1。我只注意到这不适用于任何 TypeScript 2.4+ 版本。
【问题讨论】:
标签: typescript generics contravariance typescript3.0