Tampa
Tampa

Reputation: 78264

angular2 and Typescript array - Property 'push' does not exist on type '() => void'

How do I init an empty array?

test: any[];

//On change I want to add an item to an array
test(){ 
  this.test.push('a');
}

error TS2339: Property 'push' does not exist on type '() => void'.

Upvotes: 5

Views: 38437

Answers (2)

Harrison O
Harrison O

Reputation: 1210

Try any of these solutions:

const test = [];
test.push('a');

OR

const test = [];
const name = 'a';
test.push({ 'name' : name});

You can add it to your function like:

test(name: string){
    const test = [];
    test.push({ 'name' : name});
}

Upvotes: 2

Thierry Templier
Thierry Templier

Reputation: 202196

You don't initialize your array, so test is undefined. To be able to use it, just initialize it this way:

test: any[] = [];

Upvotes: 22

Related Questions