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;
}]
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}>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With