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?
To declare an array of objects in TypeScript, set the type of the variable to {}[] , e.g. const arr: { name: string; age: number }[] = [] . Once the type is set, the array can only contain objects that conform to the specified type, otherwise the type checker throws an error. Copied!
An array of Objects is used to store a fixed-size sequential collection of elements of the same type. TypeScript Arrays are themselves a data type just like a string, Boolean, and number, we know that there are a lot of ways to declare the arrays in TypeScript.
We declare an array in Java as we do other variables, by providing a type and name: int[] myArray; To initialize or instantiate an array as we declare it, meaning we assign values as when we create the array, we can use the following shorthand syntax: int[] myArray = {13, 14, 15};
An array is a special type of data type which can store multiple values of different data types sequentially using a special syntax. TypeScript supports arrays, similar to JavaScript.
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)
.
let pieces: Piece[] = [];
//initialize object before assigning value
test(pos){
this.pieces[pos] = new Piece();
this.pieces[pos].ID = "test";
}
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