48

Error: Cannot read property 'push' of undefined in [null].

class A implements OnInit {
    stringArr: string[];

    ngOnInit() {
        for(let i=0; i<4; i++) {
            this.stringArr.push("aaa");
        }
    }
}

3 Answers 3

120

The array needs to be initialized:

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

1 Comment

I should print this and post on my desk.
32

For me the syntax was a little more than the accepted answer because I was using a full array type.

stringArr: Array<string> = [];

Also, this would work too

stringArr: string[] = [];

Just 2 ways to type a new array

1 Comment

"string" is the TypeScript string type, rather than "String".
1
class A implements OnInit {
    stringArr: string=[];
    ngOnInit() {
        for(let i=0; i<4; i++) {
            this.stringArr.push("aaa");
        }
    }
}

Here stringArr is defined as string, but not as an array of string. Define stringArr as blank array [].

1 Comment

Welcome to Stack Overflow! Please fix the formatting of your code block.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.