2016-06-22 64 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