【发布时间】:2021-08-07 12:38:06
【问题描述】:
我来自 C# 的背景,我目前正在尝试了解 Typescript。我在 Typescript 中创建通用抽象类时遇到了以下问题,我不确定这是我的实现问题还是语言限制:
给定以下抽象类,以及扩展它的类:
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);
}
}
我收到以下错误:
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[]'.
在 C# 中,我希望 apply 方法与类共享相同的泛型类型,但在 Typescript 中似乎并非如此。
如何确保Filter<string> 类型具有(items: string[]) => string[] 类型的apply 方法?
【问题讨论】:
-
为清楚起见,您的代码等同于:Playground Link - 您刚刚引入了一个 不同 通用参数,它也 称为 @987654326 @ 但不是班级的
T。我刚刚重命名了它。
标签: typescript typescript-generics