打字稿查找和过滤功能对象可能是 'undefined' 错误

typescript find and filter functions Object is possibly 'undefined' error

const [value, setValue] = React.useState(
    options.find(opt => opt.id == valueId) && options.find(opt => opt.id == valueId).title,
);

我该如何解决这个问题?

您看到此错误的原因是,如果没有元素匹配,则查找可能 return undefined。您可以使用可选链接来摆脱它:

TS Playground link

const [value, setValue] = React.useState(
    options.find(opt => opt.id == valueId)?.title,
);

Typescript 不跟踪表达式,因此 && 的左侧未被右侧考虑。


因为你不喜欢换行符,所以这样做:

const initialValue = options.find(opt => opt.id == valueId)?.title;
const [value, setValue] = React.useState(initialValue);

此用法解决了 vsCode 格式问题