使用TypeScript super()

时间:2016-06-22 02:08:28

标签: javascript oop typescript

我正在尝试在TypeScript中扩展一个类。我在编译时一直收到这个错误:'提供的参数与调用目标的任何签名都不匹配。我已经尝试在超级调用中引用artist.name属性作为超级(名称)但是不起作用。

我们将非常感谢您提出的任何想法和解释。谢谢 - 亚历克斯。

class Artist {
  constructor(
    public name: string,
    public age: number,
    public style: string,
    public location: string
  ){
    console.log(`instantiated ${name}, whom is ${age} old, from ${location}, and heavily regarded in the ${style} community`);
  }
}

class StreetArtist extends Artist {
  constructor(
    public medium: string,
    public famous: boolean,
    public arrested: boolean,
    public art: Artist
  ){
    super();
    console.log(`instantiated ${this.name}. Are they famous? ${famous}. Are they locked up? ${arrested}`);
  }
}

interface Human {
  name: string,
  age: number
}

function getArtist(artist: Human){
  console.log(artist.name)
}

let Banksy = new Artist(
  "Banksy",
   40,
  "Politcal Graffitti",
  "England / Wolrd"
)

getArtist(Banksy);

1 个答案:

答案 0 :(得分:20)

超级调用必须提供基类的所有参数。构造函数不是继承的。注释掉艺术家,因为我猜这样做是不需要的。

class StreetArtist extends Artist {
  constructor(
    name: string,
    age: number,
    style: string,
    location: string,
    public medium: string,
    public famous: boolean,
    public arrested: boolean,
    /*public art: Artist*/
  ){
    super(name, age, style, location);
    console.log(`instantiated ${this.name}. Are they famous? ${famous}. Are they locked up? ${arrested}`);
  }
}

或者,如果您希望art参数填充基本属性,但在这种情况下,我猜不需要使用public on art参数,因为属性将被继承,并且它只存储重复数据。

class StreetArtist extends Artist {
  constructor(
    public medium: string,
    public famous: boolean,
    public arrested: boolean,
    /*public */art: Artist
  ){
    super(art.name, art.age, art.style, art.location);
    console.log(`instantiated ${this.name}. Are they famous? ${famous}. Are they locked up? ${arrested}`);
  }
}