zl程序教程

您现在的位置是:首页 >  前端

当前栏目

TypeScript constructor signature 类型的变量赋值方式

typescript变量 方式 类型 赋值 constructor signature
2023-09-14 09:02:58 时间

看这段代码:

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.