看这段代码:
interface ArrayContaining {
new (sample: string): any;
}
试图给一个类型为 ArrayContaining 的变量赋值,下列这样赋值行不通:
const a: ArrayContaining = () => 1;
遇到错误消息:
Type '() => number' is not assignable to type 'ArrayContaining'.
Type '() => number' provides no match for the signature 'new (sample: string): any'.
正确的做法:
class Jerry{
constructor(private name:string){
this.name = name;
console.log('name: ', this.name);
}
}
const b: ArrayContaining = Jerry;
const c:Jerry = new b('Tom');
最后的输出:

这里的 Jerry,相当于一个构造器,具有 constructor signature,故可以赋给类型为 ArrayContaing 的 变量 b.
换句话说,TypeScript 的 class 和 constructor 关键字,具有所谓的 constructor signature.
网友评论