Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Types of property 'length' are incompatible. Type '4' is not assignable to type '1'

I'm learning typescript / angular at the moment and can't work out why TSLint is throwing this up as an error, however the code itself works and displays in a browser.

export class GreetingComponent implements OnInit {

  names: [{ name: string }] = [{ name: 'Tom' }, { name: 'Dave' }, { name: 'Katie' }, { name: 'John' }];
  constructor() { }

  ngOnInit() {
  }

Specifically the line:

 names: [{ name: string }] = [{ name: 'Tom' }, { name: 'Dave' }, { name: 'Katie' }, { name: 'John' }];

Full Error:

[ts]
Type '[{ name: string; }, { name: string; }, { name: string; }, { name: string; }]' is not assignable to type '[{ name: string; }]'.
  Types of property 'length' are incompatible.
    Type '4' is not assignable to type '1'.
(property) GreetingComponent.names: [{
        name: string;
    }]
like image 898
MissCoder87 Avatar asked Mar 29 '18 19:03

MissCoder87


2 Answers

The type:

[{name: string}]

is a tuple type of one element. So that type can only be an array with a single item in it. If you're wanting the type to be an array of any length filled with those objects, it would be written as

{name: string}[]

// Or if you prefer:

Array<{name: string}>
like image 66
CRice Avatar answered Nov 17 '22 11:11

CRice


In case of this:

names: [{ name: string }] = [{ name: 'Tom' }, { name: 'Dave' }, { name: 'Katie' }, { name: 'John' }];

You should write this:

names: { name: string }[] = [{ name: 'Tom' }, { name: 'Dave' }, { name: 'Katie' }, { name: 'John' }];

And for the second version of code it will work well.

like image 26
Guu Mee Avatar answered Nov 17 '22 13:11

Guu Mee