Reputation: 2461
I have an array of objects and when I try to access to it, I get an error saying:
TypeError: Cannot set property 'ID' of undefined
My code is the following:
export class Carimplements OnInit {
pieces: Piece[] = [];
test(pos){
this.pieces[pos].ID = "test";
}
}
being Piece an object
export class Piece{
ID: string;
doors: string;
}
I call to test(pos)
from the HTML with a valid position.
I guess that I am trying to access to the position X of an array that has not been initialized. How could I do it? Is it possible to create a constructor?
Upvotes: 15
Views: 80350
Reputation: 560
let pieces: Piece[] = [];
//initialize object before assigning value
test(pos){
this.pieces[pos] = new Piece();
this.pieces[pos].ID = "test";
}
Upvotes: 1
Reputation: 1288
How about this?
export class Carimplements OnInit {
pieces: Piece[] = [];
test(pos){
this.pieces[pos] = {ID: "test"};
}
}
Upvotes: 1
Reputation: 2526
You can try the following method
test(pos){
if(pos < this.pieces.length)
this.pieces[pos].ID = "test";
else
// throw error
}
Upvotes: 0
Reputation: 96889
Correct syntax for defining array types in TypeScript is this:
pieces: Piece[] = [];
The error is a runtime error. When you run your app you have an empty array pieces
(but the variable still initialized with []
) but you call test(whatever)
which tries to access an array element whatever
that doesn't exist.
You can do for example this:
pieces: Piece[] = [{
ID: '1',
doors: 'foo'
}];
and then test this method with test(0)
.
Upvotes: 19