web-dev-qa-db-ja.com

TypeScript super()を使用する

TypeScriptでクラスを拡張しようとしています。コンパイル時にこのエラーを受け取り続けます:「指定されたパラメーターは、呼び出し先の署名と一致しません。」 super呼び出しでartist.nameプロパティをsuper(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);
18
alex bennett

スーパーコールは、基本クラスのすべてのパラメーターを提供する必要があります。コンストラクターは継承されません。アーティストをコメントアウトしたのは、このようなことをするときには必要ないと思うからです。

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}`);
  }
}

または、アートパラメーターに基本プロパティを設定することを意図していたが、その場合、プロパティが継承され、重複データのみが格納されるため、アートパラメーターでパブリックを使用する必要は実際にはないと思います。

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}`);
  }
}
21
mollwe