Search code examples
reactjstypescriptreact-props

How to typescript Pick from array of object in React


I need do Pick from interface Order only items[] values (name, category, amount, price), pass them as props to OrderItem. I am struggling with it, probably I need to iterate over the array but I have no clue how to do it. I can't find solution over internet :(.

export interface Order {
  id: number
  user: number
  status: string
  date: string
  value: number
  number: number
  items: {
    id: number
    name: string
    category: string
    amount: number
    price: number
  }[]
}

import { Order } from '../OrderListItem/Order'

type OrderItemProps = Pick<Order['items'], 'name' | 'category' | 'amount' | 'price'>

const OrderItem = ({ name, category, amount, price }: OrderItemProps) => {
  return (
    <div className="flex justify-between">
      <p className="font-black">{name}</p>
      <p className="font-normal opacity-30">{category}</p>
      <p className="font-normal opacity-30">x{amount}</p>
      <p className="font-black text-blue-400">{price}€</p>
    </div>
  )
}

export default OrderItem

thx for your time :)

Solution

  • When you pick from Order['items'] you are picking from the Array type, not from the items model. The solution is to split the items into a separate interface:

    export interface Item {
     id: number
     name: string
     category: string
     amount: number
     price: number
    }
    
    export interface Order {
      id: number
      user: number
      status: string
      date: string
      value: number
      number: number
      items: Item[]
    }
    
    type OrderItemProps = Pick<Item, 'name' | 'category' | 'amount' | 'price'>