打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

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

关于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'.
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
GCC的扩展语法 - 中国自学编程网
javascript使用ajax请求具体步骤
3.4 其他静态工具函数
前端整理——javaScript部分
跟我学习javascript的undefined与null
python中isinstance()和type()的区别!
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服