Matt
Matt

Reputation: 43

How to declare an object of arrays in TypeScript

I'm working with Angular 4 and I want to declare a in component class an attribute, which is an object containing multiple arrays, like the following.

history: {
  Movies: Array<Media>,
  Images: Array<Media>,
  Music: Array<Media>,
}; 

The Media is an interface that looks like the following:

export interface Media {
  size: number,
  name: String
} 

When I try to push an object history elements like:

this.history.Music.push(music);

Given that music has the same type (Media).

It gives me the following error :

1449 ERROR TypeError: Cannot read property 'Music' of undefined

I guess that has something to do with the declaration.

Note: I've already tried something like:

history: {
  Movies: Array<Media>[],
  Images: Array<Media>[],
  Music: Array<Media>[],
}; 

And:

history: {
  Movies: Media[],
  Images: Media[],
  Music: Media[],
}; 

And the same error remains.

Upvotes: 2

Views: 1731

Answers (2)

Amit Chigadani
Amit Chigadani

Reputation: 29705

Initialize history object as follows, along with all the properties being set to empty array

history: {Movies: Array<Media>, Images: Array<Media>, Music: Array<Media>} = {
  Movies: [],
  Images: [],
  Music: []
};

Upvotes: 2

Rodrigo Ferreira
Rodrigo Ferreira

Reputation: 1091

I think you can create a History class:

class History {
    constructor(public Movies: Media[] = [], public Images: Media[] = [], public Music: Media[] = []){}
}

Then in your component, you can initialize your history property like this:

history = new History();

then you can do what you tried to do:

this.history.Music.push(music);

Upvotes: 0

Related Questions