2016-08-08 21 views
1

我這裏有一類:錯誤實例化時類:提供的參數不匹配通話對象的任何簽名

export class MyClass { 
    public name:string; 
    public addr:string; 

    constructor() {} 
} 

而且我在這裏導入它:

import { MyClass } from './MyClass'; 

// and use it here: 

class MyUser { 
    private _prop : MyClass[]; 

    constructor() { 
     this._prop = [ 
      new MyClass({name: 'Hello', addr: 'World'}) //<--- this is where the error appears 
     ] 
    } 
} 

當我這樣做,我得到一個短毛線的錯誤:

Supplied parameters do not match any signature of call target 

爲什麼我不能實例化我的類?

+0

看起來像是期待Typescript具有像C#那樣的對象初始化能力。但Typescript沒有:( – Vaccano

回答

1

您的MyClass構造函數中沒有提及任何參數。您必須將參數放入構造函數中,以便在實例化此類時設置值。您可以將MyClass屬性移動到構造函數parameter,使其縮短爲如下所示的語法。

export class MyClass { 
    //by having `public` on constructor shortened the syntax. 
    constructor(public name: string, public addr:string) { 

    } 
} 

constructor() { 
    this._prop = [ 
     new MyClass('Hello', 'World') 
    ] 
} 

Playground Demo

+0

仍然收到錯誤 – dopatraman

+0

@dopatraman看看更新的答案,謝謝 –

1

你應該有你的構造如下。在你的情況,你沒有定義參數:

constructor(param:{name:string, addr:string}) { 
    this.name = param.name; 
    this.addr = param.addr; 
} 

另一種辦法是在你的構造的水平來定義你的類屬性:

constructor(public name:string, public addr:string) { 
    // No need for this: 
    // this.name = name; 
    // this.addr = addr; 
} 

您現在可以通過參數構造函數和他們」將用於初始化您的實例屬性:

constructor() { 
    this._prop = [ 
    new MyClass('Hello', 'World'}) 
    ]; 
} 
相關問題