简体   繁体   中英

How to Set the properties of typescript object in angular2?

I have a typescript class defined as :

export class Atom {

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

}

I want to make an object of type Atom class and set the properties of object. For this what i am doing is

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

Error: Subsequent variable declarations must have same type. Variable atom must be of type Atom, but here it is of type any.

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

produces an error because you assign a string, image is declared as boolean though

You can also use a constructor

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

and then instantiate it with

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

or

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM