我正在try 用TypeScript扩展一个类.我在编译时一直收到这个错误:"提供的参数与调用目标的任何签名都不匹配."我试着引用这位艺术家.super中的name属性称为super(name),但不起作用.

如果您有任何 idea 和解释,我们将不胜感激.谢谢-亚历克斯.

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

推荐答案

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

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

Typescript相关问答推荐

如果存在一处房产,请确保存在其他房产

将对象属性路径描述为字符串数组的类型

如何修复VueJS中的val类型不能赋给函数

如何使用Generics保留构造函数的类型信息?

如果我有对象的Typescript类型,如何使用其值的类型?

使用React处理Websocket数据

TypeScrip表示该类型不可赋值

STypescript 件的标引签名与功能签名的区别

是否使用非显式名称隔离在对象属性上声明的接口的内部类型?

AngularJS服务不会解析传入的Json响应到管道中的模型

如何在Typescript 中组合unions ?

尽管对象的类型已声明,但未解析的变量<;变量

FatalError:Error TS6046:';--模块分辨率';选项的参数必须是:'; node ';,'; node 16';,'; node

RXJS将对键盘/鼠标点击组合做出react

类型推断对React.ForwardRef()的引用参数无效

为什么类型脚本使用接口来声明函数?他的目的是什么.

内联类型断言的工作原理类似于TypeScrip中的断言函数?

更漂亮的格式数组<;T>;到T[]

使用NextJS中间件重定向,特定页面除外

Next 13 + React 18 createContext 类型的构建问题