typescript - 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[]
?
解决方案
您需要<T>
从抽象应用方法中删除 。
如何确保某个类型的 Filter 具有类型为 (items: string[]) => string[] 的 apply 方法?
好吧,你已经在这样做了。抽象方法“应用”的定义已经在确保您的请求。将抽象类设置为泛型,所有定义的方法/道具都将继承T
具体类中的规范。
推荐阅读
- kotlin - 为什么杰克逊不能反序列化这个 JSON?
- javascript - Shopify - Slick Slider / Carousel - 响应设置不起作用
- angular - 使用 esnext 模块升级 Angular 9 后,Typescript 文件停止转换
- python - python模块未找到错误没有模块命名
- matlab - 您将如何在 MATLAB 中进行此矩阵运算?
- python - Sympy:Exp(-iHt):错误 Mutabledensematrix
- r - 如何用 R 计算子组内的出现次数?
- javascript - JavaScript:如何防止 dblclick(双击)也触发单击事件
- c# - 使用片段嵌套选项卡移动选项卡
- python - 有谁知道pytesseract的image_to_data,image_to_osd方法输出的含义?