TypeScript official document has only this short paragraph about Constructor signature:
JavaScript functions can also be invoked with the new operator. TypeScript refers to these as constructors because they usually create a new object. You can write a construct signature by adding the new keyword in front of a call signature:
JavaScript functions can also be called using the new operator. TypeScript refers to these as constructors because they usually create a new object. You can write the construction signature by adding the new keyword before the call signature:
type SomeConstructor = {
new (s: string): SomeObject;
};
function fn(ctor: SomeConstructor) {
return new ctor("hello");
}
But this example still made me confused. I fumbled for it myself and wrote an example:
type Jerry = {
score: number;
}
type SomeConstructor = {
new(s: number): Jerry;
};
class MyConstructor implements Jerry{
score: number;
constructor(score: number){
this.score = score;
}
}
function demo(ctor: SomeConstructor, number:number) {
return new ctor(number);
}
console.log('Ethan:' , demo(MyConstructor, 100));
console.log('Ethan:' , demo(MyConstructor, 200));
The following code uses the constructor signature to define a new function type:
The received input is number, and the output is a custom type Jerry.
If new is removed, it is the call signature syntax that we are already familiar with.
class MyConstructor implements the Jerry type:
MyConstructor can be regarded as a concrete realization of SomeConstructor. In this way, wherever input parameters need to be passed into SomeConstructor, I pass in MyConstructor and it will work.
The demo here is equivalent to the factory function. We can see that even though the new keyword is not explicitly used in the application code, two different instances are finally obtained:
More Jerry's original articles, all in: "Wang Zixi":
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。