How can I define an array of objects?

You are 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.

What you are looking for here is an inline interface definition for your array that defines every element in that array, whether initially present or introduced later:

let 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 [...]

If you are initializing your array with values right away, the explicit type definition is not a necessity; TypeScript can automatically infer most element types from the initial assignment:

let userTestStatus = [
    { "id": 0, "name": "Available" },
    ...
];

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

Leave a Comment