Marilou Marilou - 3 months ago 8
TypeScript Question

How can I define an array of objects in typescript?

I have created this array of objects. Can someone tell me how I could define these in typescript? Is it possible to do inline or would I need two definitions?

userTestStatus xxxx = {
"0": { "id": 0, "name": "Available" },
"1": { "id": 1, "name": "Ready" },
"2": { "id": 2, "name": "Started" }
};


I'm looking to replace the "xxx" with a definition ( I think that's the correct word ). So that later on Typescript would alert me if I used something like userTestStatus[3].nammme by mistake.

Answer

You are much better off using a native array instead of an object literal with number-like properties, so that numbering (as well as numerous other array functions) are taken care of off-the-shelf.

Anyways, you can use an inline interface definition to ensure type safety for array elements that were not initially declared:

var userTestStatus: { id: number, name: string }[] = [
    { "id": 0, "name": "Available" },
    { "id": 1, "name": "Ready" },
    { "id": 2, "name": "Started" }
];

userTestStatus[34978].nammme; // Error: Property 'nammme' does not exist on type [...]