关于typescript:什么是-TypeScript-里的-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 关键字,最初还是取得了两个不同的实例:

更多Jerry的原创文章,尽在:”汪子熙”:

【腾讯云】轻量 2核2G4M,首年65元

阿里云限时活动-云数据库 RDS MySQL  1核2G配置 1.88/月 速抢

本文由乐趣区整理发布,转载请注明出处,谢谢。

您可能还喜欢...

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据