Search code examples
angulartypescriptundefinedvariable-assignment

Type 'undefined' is not assignable to type 'CartItem'


I get the error 'Type 'undefined' is not assignable to type 'CartItem' during running my program, I could not resolve the error :(.

import { Injectable } from '@angular/core';
import { CartItem } from '../common/cart-item';
import { Subject } from 'rxjs';


@Injectable({
  providedIn: 'root',
})
export class CartService {
  cartItems: CartItem[] = [];

  totalPrice: Subject<number> = new Subject<number>();
  totalQuantity: Subject<number> = new Subject<number>();

  constructor() {}

  addToCart(theCartItem: CartItem) {
    // check if we already have the item in our cart
    let alreadyExistsInCart: boolean = false;
    let existingCartItem: CartItem = undefined; // ERROR HERE
  }
}

Type 'undefined' is not assignable to type 'CartItem' I'm getting an errorhow do I resolve this error


Solution

  • If it is just the error

    let existingCartItem: CartItem | undefined;
    

    that will initialize existingCartItem to undefined.