分享

如何理解 new (...args: any[]) => any

 汪子熙 2021-10-02

关于javascript:如何开始理解类型…args:any [])=> any

如何理解下面这段代码里的 new 操作?

/**
 * Checks if the value is an instance of the specified object.
 */
isInstance(object: any, targetTypeConstructor: new (...args: any[]) => any) {
    return targetTypeConstructor
        && typeof targetTypeConstructor ==="function"
        && object instanceof targetTypeConstructor;
}

我们逐步分解。

() => any

该函数没有输入参数,返回任意类型。

(...args: any[]) => any

...args: any[]使用的是Rest Parameters构造,该构造本质上表示可以提供any类型的任何数量的参数。因为存在数量未知的any参数,所以参数的类型是any的数组。

最后,把 new 关键字补上。

new (...args: any[]) => any

此处的new关键字指定可以将此函数视为类构造函数,并使用new关键字进行调用。

回到文章开头的函数:

该函数是一个可以接受返回类型any的任意数量的参数(类型为any的函数),并且可以用作带有new关键字的构造函数。

看一个该函数具体消费的例子:

function isInstance(object: any, targetTypeConstructor: new (...args: any[]) => any) {
    return targetTypeConstructor
        && typeof targetTypeConstructor ==="function"
        && object instanceof targetTypeConstructor;
}

class Jerry{
  constructor(private name:string){
    this.name = name;
  }
}

const jerry: Jerry = new Jerry('Jerry');

console.log(isInstance(jerry, Jerry));

输出:true

如果把 new 关键字去掉,反而会报错:

Argument of type 'typeof Jerry' is not assignable to parameter of type '(...args: any[]) => any'. Type 'typeof Jerry' provides no match for the signature '(...args: any[]): any'.

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多