美文网首页
TypeScript constructor signature

TypeScript constructor signature

作者: 华山令狐冲 | 来源:发表于2021-10-31 08:55 被阅读0次

看这段代码:

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.

相关文章

网友评论

      本文标题:TypeScript constructor signature

      本文链接:https://www.haomeiwen.com/subject/hwkjnltx.html