user1361529
user1361529

Reputation: 2697

Declaring an object property in typescript

I am trying to declare & instantiate a property that is of a object type, like so:

export class HomePage {

  @ViewChild('acc') accCanvas;
  @ViewChild('gyro') gyroCanvas;

  charts: {
    accChart: any ,
    gyroChart: any ,
  }; // problem
  acc: any;  // latest accelerometer data
  gyro: any; // latest gyro data
  logState: string = 'Start'; // button state
  stateColor: string = 'primary'; // button color
  logs: any[] = []; // will hold history of acc + gyr data

All the variables like acc, gyro etc work well and I can reference them as this.xxxx in my functions. However, I can't refer to this.charts.accChart or this.charts.gyroChart - they return as undefined. Can anyone please advise on how to declare and initialize the charts object property?

Upvotes: 0

Views: 1548

Answers (1)

ideaboxer
ideaboxer

Reputation: 4101

charts: { accChart: any, gyroChart: any } is just a type declaration. It describes the shape of the charts member. If you like to immediately access its children, you need to initialize it:

charts: {
  accChart: any,
  gyroChart: any
} = {
  accChart: void 0, // or choose an initial value other than undefined
  gyroChart: void 0 // or choose an initial value other than undefined
};

Try to avoid the any type whenever possible. Use TypeScript's types, your own types or library typings instead.

Upvotes: 2

Related Questions