简体   繁体   中英

Typescript double identifier on declaration file

I have write a class function that return the instance of myClass if it is not the instance of the class.

function myClass(){
    if ( this instanceof myClass )
        return myClass();
}

Hence, both new myClass() and myClass() and get the instance of the myClass.

myClass(); // return myClass instance
new myClass(); // return myClass instance

However, I don't know how to declare the above class in typescript declaration file.

If I write that:

class myClass{}
function myClass(): myClass;

This will be duplicate identifier error.

Is there any method to fix that? thanks!

Use different names

// Uppercase first letter!
class Greeter {
    greeting: string;
    constructor(message: string) {
        this.greeting = message;
    }
}

// lowercase first letter
function getGreeterInstance() {
    return new Greeter("Hello");
}

Explanation

  • TypeScript has its conventions, you'll save yourself a lot of headaches if you follow them.
  • Use descriptive/self-explanatory names. myClass is not clear enough for who reads the code.
  • Use different names for you definitions.

Notes

Make sure to check out TypeScript's documentation on classes and functions .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM