简体   繁体   中英

How to initialize a typed Object in TypeScript/Angular?

I'm new to Angular & TypeScript and trying to figure out how to instantiate an object (before an api request is returned with the real data).

For example, my model looks like this:

//order.model.ts
export class Order {
  constructor(public id: number, currency: string, public contact: Object, public items: Array<Object>) {}
}

And then I try to instantiate that in one of my components, let's say the App component:

//app.component.ts
export class AppComponent {
  @Input()
  public order: Order = new Order();
}

Of course, it expected to receive 4 arguments when instantiating new Order() but received 0. Do I actually have to pass in undefined/empty values for each attribute of Order?

In good ol' React (without TS) I would just initialize with an empty object and call it a day:

this.state = {
 order: {}
}

What's best practice for this sort of thing in Angular/TS?

Yes as it is currently set up you would have to pass 4 default arguments to the constructor.

public order: Order = new Order(1, '', {}, []);

Or you can set each property as nullable by adding a ? like so:

export class Order {
  constructor(public id?: number, currency?: string, public contact?: Object, public items?: Array<Object>) {}
}

If the class doesn't have functionality (you are simply using it for type checking) the best way to do it would be to declare an interface like so (you can also make them nullable here with ?s):

export interface Order {
    id: number;
    currency: string;
    contact: Object;
    items: Object[];
}

then in your component do not initialize the value until you have all of the needed values:

//app.component.ts
export class AppComponent {
  @Input()
  public order: Order;

  // just an example
  setValues(id: number, currency: string, contact: Object, items: Object[]) {
    this.order = {
      id: id,
      currency: currency,
      contact: contact,
      items: items
    }
  }

  // example for if you receive object with correct fields from backend
  getData() {
    this.service.getData().subscribe(result => {
       this.order = result;
    });
  }
}

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