gpt4 book ai didi

javascript - 使用 TypeScript super()

转载 作者:搜寻专家 更新时间:2023-10-30 20:31:15 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com