Angular 10 error: Object is possibly 'undefined' when accessing the previous array element

Viewed 4660

Angular 10, TypeScript: 3.9.7.

I'm trying to group a list of books by their CRN numbers. The "books" array is passed in the TextbooksComponent through @Input from a parent component.

My component.ts:

...
export class TextbooksComponent {
    @Input() books?: Array<Book>;
}
...

My component.html:

...
<div *ngFor="let book of books; let i=index" class="books">
    <div *ngIf="i>0 && book?.CRN === books[i-1]?.CRN; else bookCRN">
        <hr>
    </div>
    <ng-template #bookCRN>
        <h3>crn: {{ book?.CRN }}</h3>               
    </ng-template>
    <app-book
        [textbook]="book">
    </app-book>
</div>
...

I'm getting the following error when compiling, even after I use "?" to make my variables optional and checking i>0.

 ERROR in ...textbooks.component.html:16:42 - error TS2532: Object is possibly 'undefined'.

    16         <div *ngIf="i>0 && book?.CRN === books[i-1]?.CRN; else bookCRN">
                                                ~~~~~~~~~~

How do I fix this? I tried adding books?.length>1 too. It won't let me access the previous element in the array books[i-1]. I don't want to initialize and make up value for at least two elements in the books array. The data needs to be fetched from the server. Thanks.

1 Answers

You can get rid of the "possibly undefined" error by assigning default value to the input:

    @Input() books: Array<Book> = [];
Related