pmingkr
pmingkr

Reputation: 43

TypeScript: get type of instance from Function type

I want to implement getInstance into Function.prototype How can i declare type of instance

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();
};

Upvotes: 1

Views: 609

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249686

If you want this to be available on all classes, and return an instance of the class you can try the following declaration:

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 

You might want to restrict the availability of this method, right now it will be present on all classes. You could restrict that a bit, so that it is only present if a certain static member is defined (isSingleton for example):

declare global {
    interface Function 
    {
        getInstance<T>(this: { new (...args: any[]): T, isSingleton:true }): T;
    }
}
class Person {
    static isSingleton: true;
    name: string;
    public constructor(){}
}

Upvotes: 5

Related Questions