2017-01-16 48 views
-2

我有一個打字稿類定義爲:如何在angular2中設置打字稿對象的屬性?

export class Atom { 

    public text:String; 
    public image:boolean; 
    public equation:boolean; 

} 

我想使型原子類的一個對象,並設置對象的屬性。爲此我正在做的是

atom:Atom=new Atom(); 
    atom.text="hello"; 

錯誤:後續的變量聲明必須具有相同的類型。變量原子必須是Atom類型,但在這裏它是任何類型的。

回答

1
atom:Atom=new Atom(); 
atom.image="hello"; 

因爲你分配一個字符串,image被聲明爲boolean雖然

你也可以使用一個構造函數

export class Atom { 
    constructor(
    public text?:String, 
    public image?:boolean, 
    public equation?:boolean) {} 
} 

,然後用實例會產生錯誤

new Atom('someText', true, false); 

new Atom({text: 'someText'}); 
+0

如何設置特定的變量,如文本。 –

+0

我可以這樣做:atom = new Atom('someText',true,false); –

+0

然後atom.text =「Nitish」; –