当前位置:网站首页>What is the constructor signature in typescript

What is the constructor signature in typescript

2021-06-23 22:47:26 JerryWang_ Wang Zixi

TypeScript Official documents About Constructor signature It's just a short passage :

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 use new Operator call . TypeScript These are called constructors , Because they usually create a new object . You can do this by adding new Keyword to write the construction signature :

type SomeConstructor = {
  new (s: string): SomeObject;
};
function fn(ctor: SomeConstructor) {
  return new ctor("hello");
}

But this example still confuses me , I felt for myself , 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 constructor signature A new function type is defined :

The input received is number, The output is a custom type Jerry.

If you remove new, That's what we're already familiar with call signature grammar .

class MyConstructor Realized Jerry type :

MyConstructor Can be seen as SomeConstructor A concrete realization of . such , All input parameters need to be passed in SomeConstructor The place of , My biography MyConstructor go in , Can work as well .

demo Here it's equivalent to a factory function , We can see , Although not explicitly used in the application code new keyword , Finally, we get two different examples :

more Jerry The original article of , All in :" Wang Zixi ":

版权声明
本文为[JerryWang_ Wang Zixi]所创,转载请带上原文链接,感谢
https://chowdera.com/2021/06/20210623224711541m.html

随机推荐