Home > Software engineering >  Object is possible undefined? Typescript Angular
Object is possible undefined? Typescript Angular

Time:09-03

I am trying to implement this function but I keep getting this undefined error.

let item: OrderItem | undefined;

        item = this.order.items.find(o => o.productNumber === product.productNumber);

        if (item !== undefined) {
            item.quantity  ;//Error
        } else {//Something}

The error happens near the item.quantity ; These are the things I tried

if (!item) {
            item.quantity  ;

    if (item) {
        item.quantity  ;

any help is appreciated.

Order.ts

export class OrderItem {
    Id: number | undefined;
    productId: number | undefined;
    productNumber: number | undefined;
    productName: string | undefined;
    productPicture: string | undefined;
    productPrice: number | undefined;
    productDescription: string | undefined;
    quantity: number | undefined;
    unitPrice: number | undefined;
}

export class Order {
    orderId: number | undefined;
    orderNumber: string | undefined;
    orderDate: Date = new Date();
    orderTotal: number | undefined;
    /*orderStatus: string | undefined;*/
    items: OrderItem[] = [];
}

CodePudding user response:

Since quantity is typed as number | undefined item.quantity may be undefined. Trying to increment this with item.quantity would result in NaN and therefor not be what you expected here.

To satisfy the type checker here trying checking that item.quantity is not undefined:

if (item?.quantity !== undefined) {
  item.quantity  ;
}

(Note the use of optional chaining here)

  • Related