2

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

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

2 Comments

nice one I actually tried it on the othe end - items?.find((item: DropdownType) => item.id === selectedItem).label
Apart from that, why do you use == and not ===? I strongly suggest using triple equals :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.