sta*_*orn 5 generics typescript
我有一个抽象类,它有一个抽象的泛型方法,它看起来像这样
protected abstract getData<T>(): T[];
Run Code Online (Sandbox Code Playgroud)
然后我有一个扩展这个抽象类的类。由于getData是抽象的,我必须在子类中实现它。
它看起来像这样
protected getDataList<T>(): T[] {
return this.databaseService().getSomethingList();
}
Run Code Online (Sandbox Code Playgroud)
getSomethingList()返回 Something[]
虽然我收到以下错误
类型 'Something[]' 不能分配给类型 'T[]'。
我尝试了一些方法来解决此错误,但似乎必须使子实现也变得通用才能使 Typescript 满意。上述执行情况良好,直到我从升级打字稿2.2.1到2.4.1。
所以我想知道如何让我的代码再次符合 Typescript 2.4.1?
我相信您正在尝试设置它,以便整个抽象基础由派生实例必须具体化的特定类型进行参数化。以下是您将如何做到这一点:
abstract class Foo<T> {
protected abstract getData(): T[];
}
class Something { }
class SomethingFoo extends Foo<Something> {
protected getData(): Something[] {
// implement here
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,函数本身没有参数化,因为函数的调用者不是决定该函数将返回什么类型的人。相反,包含类型被参数化,并且它的任何派生指定相应的类型参数。
| 归档时间: |
|
| 查看次数: |
8439 次 |
| 最近记录: |