0

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!

1 Answer 1

1

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.

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.