TommyD
TommyD

Reputation: 1043

React typescript - object is possibly undefined

I am trying to build a dropdown component in typescript and have run into an error.

I create the type and the data.

type DropdownType = {
  id: number;
  label: string;
};
const data: DropdownType[] = [
  { id: 0, label: "Istanbul, TR (AHL)" },
  { id: 1, label: "Paris, FR (CDG)" },
];

the set the initial data

  const [items, setItem] = useState<DropdownType[]>(data);

However typescript tells me it is possibly undefined

 {selectedItem
          ? items.find((item: DropdownType) => item.id === selectedItem).label
          : "Select your destination"}

Any idea what I am doing wrong?

https://codesandbox.io/s/morning-leftpad-5ohhv?file=/src/Dropdown.tsx:1609-1741

Upvotes: 2

Views: 778

Answers (1)

Sinan Yaman
Sinan Yaman

Reputation: 5946

It is because of the fact that .find function returns undefined if the condition is never met. So:

items.find((item: DropdownType) => item.id === selectedItem)

can return undefined. You can use conditional chaining:

items.find((item: DropdownType) => item.id === selectedItem)?.label

Upvotes: 4

Related Questions