1

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();
};
3
  • Function is the own object? you want add new method to this object prototype? Commented Feb 10, 2018 at 8:31
  • yes, I implemented getInstance into many class as static method., I realized i can make it more easier Commented Feb 10, 2018 at 8:42
  • Please note that this is extremely bad design. Commented Feb 10, 2018 at 10:23

1 Answer 1

5

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(){}
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.