Mr. Toast
Mr. Toast

Reputation: 1869

How can i push to an custom typed array

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

Answers (2)

Chad Allard
Chad Allard

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"}] 

Typescript Playground Example

Upvotes: 0

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

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

Related Questions