Reputation: 1869
Im using Angular 5 with typescript 2.7.1. In typescript i have a custom type
arr: {id: string; name: string; }[];
and i want to push an element to the array, and have tried the following:
this.arr.push({id: "text", name: "text"})
ERROR TypeError: Cannot read property 'push' of undefined
let array2 : {id: "id", name: "name"}
this.arr.push(array2)
ERROR TypeError: Cannot read property 'push' of undefined
I don't understand why it wont work, I am defining id and name in push, I just want to add more elements to the array, am i missing something?
Upvotes: 0
Views: 838
Reputation: 21
I just ran into this myself and it wasn't initially clear to initialize the array. Once you do that, the array can accept objects of its type:
type arr = {id: string, name: string}
const array1: arr[] =[];
const array2: arr = {id: "id", name: "name"}
array1.push(array2);
console.log(array1) // prints [{"id": "id","name": "name"}]
Upvotes: 0
Reputation: 249466
You need to initialize the array with an empty array before you use the field:
this.rows = [];
Or directly upon declaration
rows: {id: string; name: string; }[] = [];
Upvotes: 3