【发布时间】:2023-03-15 14:50:02
【问题描述】:
如何声明find方法的返回类型?
class Base{
find(){
return new this()
}
}
由于find 返回自我类实例,它不能硬编码为:Base。例如,如果我从 Base 继承 Child 类,则 Child.find() 必须返回 Child 类型,而不是 Base。
class Base{
static find(): Base{ // this is incorrect
return new this()
}
}
我尝试使用下面的泛型,但出现 TS2302 错误。那么正确的做法是什么?
class Base<T>{
static find(): T{ // ERROR: TS2302
return new this()
}
}
【问题讨论】:
标签: typescript generics typescript-typings