分享

什么是 TypeScript 里的 Constructor signature

 汪子熙 2021-06-23

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 关键字,最后还是获得了两个不同的实例:

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章