当前位置: 代码网 > it编程>编程语言>Javascript > 详解什么是TypeScript里的Constructor signature

详解什么是TypeScript里的Constructor signature

2024年05月15日 Javascript 我要评论
constructor signaturetypescript官方文档里关于 constructor signature 只有这短短的一段话:javascript functions can also

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的资料请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com