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

举报
汪子熙 发表于 2022/08/01 21:51:56 2022/08/01
【摘要】 如何理解下面这段代码里的 new 操作?/** * Checks if the value is an instance of the specified object. */isInstance(object: any, targetTypeConstructor: new (...args: any[]) => any) { return targetTypeConstructor...

如何理解下面这段代码里的 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’.

【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。