Construct Signature

When a function in JavaScript is called with the new keyword, the function will be used as a constructor. In order for this behavior to be reflected in TypeScript, you must provide a construct signature for your constructor function:

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
interface CatConstructor {
// Construct signature
new(name: string): ICat;
}

interface ICat {
name: string;
meow(): string;
}

// Turning function into constructor function
const Cat = function (this: ICat, name: string) {
this.name = name;
} as unknown as CatConstructor;

// Prototype-based programming
Cat.prototype.meow = function (): string {
return 'Meow!';
};

const myCat = new Cat('Joey');
console.log(myCat.name); // "Joey"
console.log(myCat.meow()); // "Meow!"