网站搜索

reactjs - React typescript - 对象可能未定义


我正在尝试在 TypeScript 中构建一个下拉组件,但遇到了一个错误。

我创建类型和数据。

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

设置初始数据

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

然而 TypeScript 告诉我它可能未定义

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

你知道我哪里做错了吗?

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

答案#1

这是因为如果条件从未满足,.find 函数会返回 undefined。所以:

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

可以返回未定义。你可以使用 条件链:

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