我想将getInstance
实施到Function.prototype
我如何声明实例类型
module global
{
declare interface Function
{
getInstance():new of this; /// Can i declare it?
}
}
Function.prototype.getInstance = function(){
if (this.instance) return this.instance;
return this.instance = new this();
};
答案 0 :(得分:4)
如果您希望所有类都可以使用它,并返回该类的实例,您可以尝试以下声明:
declare global {
interface Function
{
// Available on all constructor functions with no argumnets, `T` will be inferred to the class type
getInstance<T>(this: new ()=> T): T;
}
}
class Person {
name: string;
}
let p = Person.getInstance(); // p is Person
let pName = p.name // works
您可能希望限制此方法的可用性,现在它将出现在所有类中。您可以对此进行限制,以便仅在定义了某个静态成员时才会出现(例如isSingleton
):
declare global {
interface Function
{
getInstance<T>(this: { new (...args: any[]): T, isSingleton:true }): T;
}
}
class Person {
static isSingleton: true;
name: string;
public constructor(){}
}