typescript - TypeScript 静态成员返回相同的类实例?
问题描述
如何声明find
方法的返回类型?
class Base{
find(){
return new this()
}
}
作为find
返回 self 类实例,它不能硬编码为:Base
. 例如,如果我Child
从 Base 继承类而不是 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中的方法或成员目前没有多态;this
static
有关详细信息,请参阅microsoft/TypeScript#5863。
解决方法是使静态方法通用并给它一个this
参数:
class Base {
static find<T extends Base>(this: new () => T): T {
return new this(); // no-arg constructor
}
}
这应该如你所愿:
class GoodSub extends Base {
foo = "bar";
}
const goodSub = GoodSub.find(); // GoodSub
console.log(goodSub.foo.toUpperCase()); // BAR
如果您尝试在其构造函数需要参数的子类上使用它,它会抱怨:
class BadSub extends Base {
constructor(public bar: string) {
super();
}
}
const badSub = BadSub.find(); // error!
// ----------> ~~~~~~
// typeof BadSub is not assignable to new () => BadSub
console.log(badSub.bar.toUpperCase()); // error at runtime, badSub.bar is undefined
好的,希望有帮助;祝你好运!Playground 代码链接
推荐阅读
- python - 如何使这两个命令都可以放入 discord.py
- javascript - 如何使用 d3.js 绘制螺旋气泡图
- c++ - 为什么我不能直接将字符串文字作为非类型模板参数传递?
- python - 从 %-style 格式字符串模板中提取键
- python - 如何修复 PyGame 中闪烁的绘图?只更新一次屏幕
- google-secret-manager - 获取最新版本的应用引擎云密文的好方法是什么?
- attributes - 为什么会出现此属性错误,解决方法是什么
- c# - ML.NET 如何检测 C# 中方法链的结尾?
- java - Elasticsearch Java:无法为对象堆错误保留足够的空间
- typescript - 当与字符串原始类型联合时,使打字稿显示字符串文字的类型提示