【问题标题】:Typescript generic abstract class - Why doesn't this abstract method inherit the class type?Typescript 通用抽象类 - 为什么这个抽象方法不继承类类型?
【发布时间】: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&lt;string&gt; 类型具有(items: string[]) =&gt; string[] 类型的apply 方法?

【问题讨论】:

  • 为清楚起见,您的代码等同于:Playground Link - 您刚刚引入了一个 不同 通用参数,它 称为 @987654326 @ 但不是班级的T。我刚刚重命名了它。

标签: typescript typescript-generics


【解决方案1】:

您需要从抽象应用方法中删除&lt;T&gt;

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

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

【讨论】:

    【解决方案2】:

    您无需向apply 提供通用参数。您的代码的以下修改编译没有问题。

    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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多