当前位置:网站首页>如何理解 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’.
边栏推荐
- KMP 字符串匹配问题
- seaborn笔记:可视化统计关系(散点图、折线图)
- shell programming conventions and variables
- Mini Program--Independent Subcontracting & Subcontracting Pre-download
- 程序员必备的 “ 摸鱼神器 ” 来了 !
- 0DFS Medium LeetCode6134. Find the closest node to the given two nodes
- 使用分类权重解决数据不平衡的问题
- Lecture 3: Several common table field data types in MySQL database
- 小程序--分包
- Based on php online music website management system acquisition (php graduation design)
猜你喜欢
SAP ABAP OData 服务如何支持删除(Delete)操作试读版
多商户商城系统功能拆解19讲-平台端发票管理
Port protocol for WEB penetration
seaborn笔记:可视化统计关系(散点图、折线图)
基于php动漫周边商城管理系统(php毕业设计)
Based on php online music website management system acquisition (php graduation design)
HCIP---Architecture of Enterprise Network
scikit-learn no moudule named six
Pagoda application experience
[ASM] Bytecode Operation MethodWriter
随机推荐
C语言必杀技3行代码把运行速度提升4倍
kubernetes CoreDNS全解析
[Mobile Web] Mobile terminal adaptation
Spark shuffle调优
scikit-learn no moudule named six
more grown, more lonely
Port protocol for WEB penetration
第3讲:MySQL数据库中常见的几种表字段数据类型
Homework 8.1 Orphans and Zombies
基于php在线考试管理系统获取(php毕业设计)
漫长的投资生涯
SAP ABAP OData 服务如何支持删除(Delete)操作试读版
如何防范 DAO 中的治理攻击?
NFT的10种实际用途(NFT系统开发)
SOM网络1:原理讲解
365 days challenge LeetCode1000 questions - Day 046 Generate a string with odd number of each character + add two numbers + valid parentheses
Today's sleep quality record 74 points
今年的很美味
dvwa 通关记录1 - 暴力破解 Brute Force
递归(各经典例题分析)