[英]Typescript generic abstract class - Why doesn't this abstract method inherit the class type?
I come from a background in C# and I'm currently trying to get my head around Typescript.我来自 C# 的背景,我目前正试图了解 Typescript。 I've run in to the following issue while creating a generic abtract class in Typescript, and I'm not sure if it's a problem with my implementation, or a limitation of the language:
我在 Typescript 中创建通用抽象 class 时遇到了以下问题,我不确定这是我的实现问题还是语言限制:
Given the following abstract class, and class extending it:给定以下抽象 class 和 class 扩展它:
abstract class Filter<T> {
value T;
abstract apply<T>(items: T[]): T[];
}
class StringFilter extends Filter<string> {
apply(items: string[]) {
return items.filter(i => this.value === i);
}
}
I get the following error:我收到以下错误:
Property 'apply' in type 'StringFilter' is not assignable to the same property in base type 'Filter<string>'.
Type '(items: string[]) => string[]' is not assignable to type '<T>(items: T[]) => T[]'.
In C# I would have expected the apply method to share the same generic type as the class, but in Typescript this doesn't seem to be the case.在 C# 中,我希望 apply 方法与 class 共享相同的泛型类型,但在 Typescript 中似乎并非如此。
How can I make sure that a type of Filter<string>
has an apply method of type (items: string[]) => string[]
?如何确保某种类型的
Filter<string>
具有类型为(items: string[]) => string[]
的 apply 方法?
You need to remove the <T>
from the abstract apply method.您需要从抽象应用方法中删除
<T>
。
How can I make sure that a type of Filter has an apply method of type (items: string[]) => string[]?
如何确保某个类型的 Filter 具有类型为 (items: string[]) => string[] 的 apply 方法?
Well, you're already doing that.好吧,你已经在这样做了。 The definition of the abstract method "apply" is already ensuring your request.
抽象方法“应用”的定义已经在确保您的请求。 Setting the abstract class as generic, all the methods/props defined will inherit the
T
specification in the concrete class.将抽象 class 设置为泛型,所有定义的方法/道具将继承具体 class 中的
T
规范。
You don't need to provide the generic parameter to apply
.您无需提供通用参数即可
apply
。 The following modification of your code compiles without issues.您的代码的以下修改编译没有问题。
abstract class Filter<T> {
value: T;
abstract apply(items: T[]): T[];
}
class StringFilter extends Filter<string> {
apply(items: string[]) {
return items.filter(i => this.value === i);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.