Visual Studio Code highlights error

[ts] Тип "[{ name: string; year: number; }, { name: string; year: number; }, { name: string; year: number; }]" не может быть назначен для типа "[{ name: string; year: number; }]". Типы свойства "length" несовместимы. Тип "3" не может быть назначен для типа "1". (property) name: string 

Here is the part of the code

 cars: [{name: string, year: number}] = [{ name: 'Ford', year: 2015 }, { name: 'Mazda', year: 2010 }, { name: 'Audi', year: 2017 }]; 

What is wrong here?

    3 answers 3

    The variable cars declared with the type: [{name: string, year: number}]

    That is, an array with a single element having a string name field and a number field number .

    In this case, an attempt is made to assign a value of the type of an array with three elements. These types are not compatible, as they have different lengths.

    To solve, you must either specify the square brackets after the element type:

     cars: {name: string, year: number}[] 

    Or use generic type Array

     cars: Array<{name: string, year: number}> 

      I think that should work fine.

       interface Car { name: string, year: number } let cars: Array<Car> = [{ name: 'Ford', year: 2015 }, { name: 'Mazda', year: 2010 }, { name: 'Audi', year: 2017 }]; 
      • one
        Can you explain why my version does not work? - Slava
      • one
        @Slava, you declared a variable of type array with one element , and tried to assign to it a value of type array with three elements . - Grundy

      cars: {name: string, year: number}[] - in ts, an array in types is denoted as [] at the end of a string