typescript - TypeScript - 返回父类中子对象的类型?(单例的类型)
问题描述
我有以下问题。在打字稿中,我为单例创建了抽象类,但我正在寻找正确的响应类型。
abstract class Singleton {
private static _instance: any;
static get instance(): any {
if (!this._instance) {
var me: any = this;
this._instance = new me();
}
return this._instance;
}
}
class Test extends Singleton {
public test(): string {
return "hello world";
}
}
var testInstance = Test.instance;
// then testInstance dont support intellisence of supported methods
实际上我使用了“any”,但是当我调用实例时,它在逻辑上没有显示任何子方法/道具。我正在寻找写一些像“儿童”而不是“任何”这样的想法的可能性——在 TypeScript 中是否有类似的定义?
谢谢你的任何建议。
解决方案
你可以使用泛型。由于您不能在属性上使用泛型,get instance()
因此getInstance()
.
abstract class Singleton {
private static _instance: any;
static getInstance<T>(): T{
if (!this._instance) {
var me: any = this;
this._instance = new me();
}
return this._instance as T;
}
}
class Test extends Singleton {
public test(): string {
return "hello world";
}
}
var testInstance = Test.getInstance<Test>();
推荐阅读
- c++ - 我需要哪些 DLL 和库才能使用“timeBeginPeriod”或“timeapi.h”的其他部分?
- ruby-on-rails - Rspec 种子作业在模型验证后运行
- python - tqdm 将我的程序减慢了至少 8 倍
- reactjs - React.js:在 API 响应中访问 Retry-After 标头
- heap - 带有伪代码的堆和优先级队列
- android - 如何在 Android 的 camera2 中正确使用新的 createCaptureSession()?
- elasticsearch - Elasticsearch 中复合查询中的自定义评分函数
- .net - 在 WinForms 上打开 RDLC 时如何解决问题?
- c# - 给定的程序集名称或代码库“System.Data.SqlServerCe”无效。不知道为什么
- java - 在底部导航视图中添加 Textview