JavaScript supports two basic data structures for storing information, Arrays and Hashes. Let's look at how we might add an Array and a Hash to a View Model.

Arrays

TypeScript arrays can be defined and initialized in two ways, with the Array<T> type, or T[] type. Both of these are equivalent, but one or the other may be easier to write depending on the situation.

So, if we were to create an Array of string elements, it would be.

let list: string[] = [];

This code simply creates an variable called list, defined as an string[] and initializes it to be an empty Array. It is important to note that we have initialized this variable, otherwise it would equal undefined.

Now that we have created an Array, we can access its values with a regular Assignment Operator. We can read and write values with:

let value = list[0];
list[1] = 2;

We can also use any of the Array methods, such as Array.prototype.push(value: any): void;

list.push(3);

Hashes

Next, we have JavaScript Hashes, which are actually just regular Objects.

TypeScript Hashes can be defined as an interface, which stores elements with either string or number indexes. JavaScript allows for mixing index types, but TypeScript requies it to be one or the other.

For more information on Arrays, visit Array - JavaScript | MDN

For more information on Objects, visit Objects - JavaScript | MDN

View Models

We may store Arrays and Hashes as properties on a View Model. For example:

class ViewModel {
    list = [];
    map = {};
}

However, just like regular properties, changes to these properties will be ignored. Again, if we add our decorators, we can subscribe to changes.

class ViewModel {
    @observable list = [];
    @observable map = {};
}

We can also be more specific about what is stored in Arrays and Hashes.

class ViewModel {
    @observable list: string[];
    @observable map: {
        [index: string]: string
    };
}