2016-06-22 63 views
5

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

您可能会有任何想法和解释将不胜感激。谢谢 - 亚历克斯。

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

**解答:请参阅下面的@mollwe的答案。 –

回答

6

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

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

如果你为每个构造函数参数添加了公共元素,那么这个参数将被分配给子元素以及父元素 –

+0

我确实打算用art:Artist来填充基类。第二种解决方案无缝工作。非常感谢你。 –

+0

很高兴能够提供帮助。 @morteza你是对的,它意味着有前四个参数没有公开。我不知道如果您将StreetArtist投入艺术家和访问名称会发生​​什么情况,他们会一样吗?它隐藏了基础产权? – mollwe