Search code examples
typescript

How can I define an array of objects?


I am creating an array of objects in TypeScript:

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

Can someone tell me how I could declare its type correctly? Is it possible to do inline or would I need two definitions?

I'm looking to replace the xxx with a type declaration, so that later on TypeScript would alert me if I used something like userTestStatus[3].nammme by mistake.


Solution

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