Ali Shakiba
Ali Shakiba

Reputation: 21277

TypeScript: Definition for constructor with and without `new`?

What is TypeScript definition for following code?

function MyClass (arg) {
  if (!(this instanceof MyClass)) {
    return new MyClass(arg);
  }
  //...
}

I need definition to support calling both new MyClass('Name') and MyClass('Name').

Upvotes: 0

Views: 38

Answers (1)

Matt McCutchen
Matt McCutchen

Reputation: 30929

If you are writing a TypeScript declaration file for a function defined in JavaScript, you would write:

declare const MyClass: {
  (arg: /*arg type here*/): MyClass;
  new (arg: /*arg type here*/): MyClass;
};

If you are defining the function in TypeScript, you would write:

const MyClass2 = <{
  (arg: number): MyClass;
  new (arg: number): MyClass;
}> function (arg) {
    /* definition */
};

Either way, you'll need a separate interface MyClass declaration for the type of the instances.

Upvotes: 1

Related Questions