gpt4 book ai didi

Typescript 泛型抽象类 - 为什么这个抽象方法不继承类类型?

转载 作者:行者123 更新时间:2023-12-03 21:05:14 36 4
gpt4 key购买 nike

我来自 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 提供泛型参数。 .您的代码的以下修改编译没有问题。

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

关于Typescript 泛型抽象类 - 为什么这个抽象方法不继承类类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67583427/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com