title: Trying to determine the best way to enforce a strict TypeScript null check for function
body: <p>I have a TypeScript utility function I've written that takes an Item object in an array, and appends a <em>quantity</em> property that increases by 1 for every duplicate Item of that kind that is added to that array.</p>
  <p>The problem I'm running into is that I'm already using the spread operator within the function and I'm still getting the TypeScript error stating <code>Object is possibly undefined</code>.</p>
  <p>I'm not sure how to get around this without writing something verbose to check  <code>if cartItem &amp;&amp; (...rest of my function)</code></p>
  <p><strong>EDIT: Version of TypeScript in my project is 3.9.7</strong></p>
  <p><code>Current Function</code></p>
  <pre><code>import { Item } from &quot;../../pages/shop/shop.component&quot;;
  
  export const addItemToCart = (cartItems: Item[], cartItemToAdd: Item) =&gt; {
    const existingCartItem = cartItems.find(
      (cartItem: Item) =&gt; cartItem.id === cartItemToAdd.id
    );
  
    if (existingCartItem) {
      return cartItems.map((cartItem) =&gt;
        cartItem.id === cartItemToAdd.id
          // Error on this line at ? {...cartItem, quantity: cartItem.quantity + 1}
          ?  { ...cartItem, quantity: cartItem.quantity + 1 }
          : cartItem
      );
    }
  
    return [...cartItems, { ...cartItemToAdd, quantity: 1 }];
  };
  </code></pre>