skip to Main Content

How to initialise empty object array in TypeScript?

Code:

let data: [{productID: number, vendorID: number}] = [];

Compilation error:

Type '[]' is not assignable to type '[{productID: number, vendorID: number}]'.

2

Answers


  1. The format you have written is a tuple with one-element, try this instead:

    let data: Array<{ productID: number, vendorID: number }> = [];
    

    Alternatively:

    let data: { productID: number; vendorID: number }[] = [];
    
    Login or Signup to reply.
  2. defince a type first Product then declare an array of that type:

    interface Product{
        productID: number;
        vendorID: number
    }
    let data:Product[]=[]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search