javascript - 使用 TypeScript super()

标签 javascript oop typescript

我正在尝试在 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);

最佳答案

super 调用必须为基类提供所有参数。构造函数不被继承。注释掉艺术家,因为我想这样做时不需要它。

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 参数填充基本属性,但在那种情况下,我想实际上没有必要在 art 参数上使用 public,因为属性将被继承,并且它只会存储重复数据。

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

关于javascript - 使用 TypeScript super(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37957404/

相关文章:

javascript - "ReferenceError: Can' t 查找变量 : google"on checking for undefined

javascript - 使用 django 在 JS 中获取和使用 python 嵌套列表

javascript - 使用 "onmouseover"的描述框

PHP json_encode 和 javascript 函数

model-view-controller - 做MVC还是不做?

php - 使子类继承基类的现有实例

reactjs - 找不到 'bson' 的类型定义文件。该文件在程序中,因为 : Entry point for implicit type library 'bson'

typescript - TypeScript 中 lambda 返回类型的签名

javascript - 循环对象值按预期工作,但第一个值未定义?

typescript - 如何将 `VueI18n` 与 typescript 和 `vue2.0` 一起使用? `new VueI18n({..})` 报告 `has no construct signatures`错误