Search code examples
angulartypescripttypesundefined

Typescript : Type is not assignable to type


I'm getting the below error for this TypeScript code :

getTollById(id: number): Toll {
  return this.toll
    .filter(toll => toll.id === id)
    .pop();

}

 

Solution

  • 👋🏻 @DarBen,

    The array method, filter, returns an array inferred from the instance. This could return an empty array. When using pop() on an empty array, you will get undefined as seen here.

    Also, the use of pop will not affect the list of TODOs. I'm not sure if you were thinking the todos array would be affected? The first playground link demonstrates that.

    If you are just looking to find the todo in the list, you can use the find method, which does the same as filter followed by pop, but IMO shows that you are looking for an item without the ambiguity that the original array might be affected. Here is a complete example.