Home > Software design >  How to type safe filtered array of objects with possible undefined key value
How to type safe filtered array of objects with possible undefined key value

Time:09-23

interface Item {
  quantity?: number;
}

interface CartItem {
  quantity: number;
}

const items: Record<string, Item> = {
  item1: {
    quantity: 2
  },
  item2: {},
}

const filteredItems = Object.values(items).filter(({quantity = 0}) => (quantity > 0)).forEach(item => {
  const cartItem: CartItem = {
    // Type 'number | undefined' is not assignable to type 'number'.
    // Type 'undefined' is not assignable to type 'number'.ts(2322)
    quantity: item.quantity,
  }
})

I'm currently trying to filter object keys that has quantity into an array. I successfully filtered the objects without any quantity but I seem to get typing errors even if I filtered my Item objects with quantity that does not exist or equal to 0. How can I make it avoid getting these type errors?

CodePudding user response:

You can use the user-defined type guard feature of Typescript.

const filteredItems = Object.values(items)
  .filter((i): i is Required<Item> => "quantity" in i)
  .map(item => {
  const cartItem: CartItem = {
    quantity: item.quantity,
  }
});
  • Related