[About javascript: How to start understanding types...args: any [])=> any]( https://www.codenong.com/50726326/)
How to understand the new operation in the following code?
/**
* 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;
}
We gradually break down.
() => any
This function has no input parameters and returns any type.
(...args: any[]) => any
...args: any[] uses the Rest Parameters construction, which essentially means that any number of parameters of any type can be provided. Because there are an unknown number of any parameters, the type of the parameters is an array of any.
Finally, add the new keyword.
new (...args: any[]) => any
The new keyword here specifies that this function can be regarded as a class constructor and can be called using the new keyword.
Back to the function at the beginning of the article:
This function is a function that can accept any number of parameters with return type any (a function of type any), and can be used as a constructor with the new keyword.
Look at an example of the specific consumption of this function:
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));
Output: true
If the new keyword is removed, an error will be reported instead:
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'.
More original articles by Jerry, all in: "Wang Zixi":
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。