5

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'.

2 Answers 2

22

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

test: any[] = [];
Sign up to request clarification or add additional context in comments.

2 Comments

I have the same issue as IntelliJ warning, but it's probably just an IntellIJ bug. The TypeScript compiler does not complain about it.
I wanted to comment on Thierry's reply, but lack of reputation. You must use the same typescript version in your IDE as the version in angular config, to avoid seeing any syntax errors and code-completion suggestion.
2

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});
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.