15

I have an array of objects and when I try to access to it, I get an error saying:

TypeError: Cannot set property 'ID' of undefined

My code is the following:

export class Carimplements OnInit {
  pieces: Piece[] = [];

  test(pos){
    this.pieces[pos].ID = "test";
  }
}

being Piece an object

export class Piece{
    ID: string;
    doors: string;
}

I call to test(pos) from the HTML with a valid position.

I guess that I am trying to access to the position X of an array that has not been initialized. How could I do it? Is it possible to create a constructor?

2
  • Don't you mean this to be: pieces: Piece[] = [];? Commented Mar 19, 2018 at 11:26
  • Yes sorry, that's been just a typo. But the error keeps persisting. Commented Mar 19, 2018 at 11:29

4 Answers 4

19
  • Correct syntax for defining array types in TypeScript is this:

    pieces: Piece[] = [];
    
  • The error is a runtime error. When you run your app you have an empty array pieces (but the variable still initialized with []) but you call test(whatever) which tries to access an array element whatever that doesn't exist.

    You can do for example this:

    pieces: Piece[] = [{
      ID: '1',
      doors: 'foo'
    }];
    

    and then test this method with test(0).

Sign up to request clarification or add additional context in comments.

2 Comments

pieces = Piece[] = [] was just a typo. I meant pieces: Piece[] = []; But the error keeps persisting.
Can you make a demo?
1

How about this?

export class Carimplements OnInit {
  pieces: Piece[] = [];

  test(pos){
    this.pieces[pos] = {ID: "test"};
  }
}

Comments

1
let pieces: Piece[]  = [];

//initialize object before assigning value
test(pos){
    this.pieces[pos] = new Piece();
    this.pieces[pos].ID = "test";
  }

Comments

0

You can try the following method

 test(pos){
    if(pos < this.pieces.length)
      this.pieces[pos].ID = "test";
    else
      // throw error
  }

1 Comment

No. Pos is correct. Actually in this case I am trying to access to pos = 0, which is the first one.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.