首页 > 解决方案 > Typescript 通用抽象类 - 为什么这个抽象方法不继承类类型?

问题描述

我来自 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[]

标签: typescripttypescript-generics

解决方案


您需要<T>从抽象应用方法中删除 。

如何确保某个类型的 Filter 具有类型为 (items: string[]) => string[] 的 apply 方法?

好吧,你已经在这样做了。抽象方法“应用”的定义已经在确保您的请求。将抽象类设置为泛型,所有定义的方法/道具都将继承T具体类中的规范。


推荐阅读