当前位置:网站首页>如何理解 new (...args: any[]) => any
如何理解 new (...args: any[]) => any
2022-08-01 21:54:00 【华为云】
如何理解下面这段代码里的 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’.
边栏推荐
猜你喜欢
随机推荐
365天挑战LeetCode1000题——Day 046 生成每种字符都是奇数个的字符串 + 两数相加 + 有效的括号
求解多元多次方程解的个数
Based on php animation peripheral mall management system (php graduation design)
SOM网络1:原理讲解
多商户商城系统功能拆解19讲-平台端发票管理
shell规范与变量
微软校园大使喊你来秋招啦!
kubernetes CoreDNS全解析
[ASM] Bytecode Operation MethodWriter
【牛客刷题-SQL大厂面试真题】NO4.出行场景(某滴打车)
(*゚ヮ゚)*【精品C语言整理】*(゚ヮ゚*)女盆友缠着你让你教她写代码怎么办?安排,三万字博文带你走遍C语言,从此不再害怕编程
Scala practice questions + answers
AQS
Yizhou Financial Analysis | The intelligent transformation of bank ATM machines is accelerated; the new Internet loan regulations bring challenges
Appendix A printf, varargs and stdarg a. 2 use varargs. H to realize the variable argument list
9. SAP ABAP OData 服务如何支持删除(Delete)操作
基于php在线学习平台管理系统获取(php毕业设计)
The Microsoft campus ambassador to shout you to autumn recruit!
使用分类权重解决数据不平衡的问题
【C语言实现】整数排序-四种方法,你都会了吗、