constructor signature
typescript 官方文档里关于 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 函数也可以使用 new 运算符调用。 typescript 将这些称为构造函数,因为它们通常会创建一个新对象。
编写构造签名
您可以通过在调用签名前添加 new 关键字来编写构造签名:
type someconstructor = {
new (s: string): someobject;
};
function fn(ctor: someconstructor) {
return new ctor("hello");
}但这个例子还是看得我一头雾水,自己摸索了一下,写了一个例子:
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));定义新的函数类型
下面的代码使用 constructor signature 定义了一个新的函数类型:

接收的输入是 number,输出是自定义类型 jerry.
如果去掉 new,就是我们已经熟悉的 call signature 语法.
class myconstructor 实现了 jerry 类型:

myconstructor 可以看成 someconstructor 的一种具体实现。
这样,凡是输入参数需要传入 someconstructor 的地方,我传 myconstructor 进去,一样能够工作。

demo 在这里相当于工厂函数,我们可以看到,尽管应用代码里没有显式使用 new 关键字,最后还是获得了两个不同的实例:

以上就是详解什么是typescript里的constructor signature的详细内容,更多关于typescript constructor signature的资料请关注代码网其它相关文章!
发表评论