Typescript react, arrays of different types problem

Viewed 258

Hello I have a problem I have 2 arrays of different types one is array of objects, the second is an array of string. I want to map through these 2 arrays. Get the name property from the first and the just item from the second one. I wanted to check if props.items.name exists but the problem I can use the "name" property.

interface funcProps {
  items: ingredient[] | string[];
}

const ListBox: React.FC<funcProps> = (props) => {
  const thereIsNoItem = props.items.length === 0;
  return (
    <Box
      border="1px"
      borderColor="gray.200"
      padding="1rem"
      marginTop="1rem"
      marginBottom="1rem"
    >
      <Heading>Ingredients</Heading>
      {thereIsNoItem && <h1>No ingredients was added yet</h1>}
      {!thereIsNoItem &&
        props.items.map((item, index) => (
          <IngredientItem
            key={index}
            ingredientName={item.name || item}
            numberOfIngredient={index + 1}
          />
        ))}
    </Box>
  );
};
1 Answers
interface funcProps {
  items: ingredient[] | string[];
}

const ListBox: React.FC<funcProps> = (props) => {
  const thereIsNoItem = props.items.length === 0;
  return (
    <Box
      border="1px"
      borderColor="gray.200"
      padding="1rem"
      marginTop="1rem"
      marginBottom="1rem"
    >
      <Heading>Ingredients</Heading>
      {thereIsNoItem && <h1>No ingredients was added yet</h1>}
      {!thereIsNoItem &&
        props.items.map((item, index) => (
          <IngredientItem
            key={index}
            ingredientName={typeof item === "object" ? item.name : item}
            numberOfIngredient={index + 1}
          />
        ))}
    </Box>
  );
};

It works I have done it something like this.

Related