为何已添加检查,TypeScript仍提示属性可能为undefined?
为什么TypeScript在已检查url存在后仍提示可能为undefined?
你的代码
const handleClick = (index: number) => () => { const hasUrl = !!searchTypes[index]?.url if (hasUrl) { router.push(searchTypes[index]?.url); } else { setSelectedSearchType(index); } };
遇到的错误
(property) url?: string | undefined
Argument of type 'string | undefined' is not assignable to parameter of type 'Url'.
Type 'undefined' is not assignable to type 'Url'.
问题原因
TypeScript的类型收窄机制只认当前作用域内直接关联的变量检查。你把searchTypes[index]?.url的存在性判断结果存到了独立变量hasUrl里,TS没办法把hasUrl的真值和后续调用的searchTypes[index]?.url绑定起来——它无法保证在检查hasUrl之后,searchTypes数组或者对应索引的url属性没被修改,所以依然认为这个值可能是undefined。
修复方案
方案1:缓存目标元素再检查
先把searchTypes[index]存到一个变量里,后续操作都基于这个变量,TS就能正确跟踪它的类型:
const handleClick = (index: number) => () => { const currentType = searchTypes[index]; if (currentType?.url) { router.push(currentType.url); } else { setSelectedSearchType(index); } };
方案2:直接在条件中检查属性
去掉单独的hasUrl变量,直接在if条件里判断目标属性,让TS直接收窄后续代码的类型:
const handleClick = (index: number) => () => { if (searchTypes[index]?.url) { router.push(searchTypes[index]?.url); } else { setSelectedSearchType(index); } };
如果searchTypes是不可变数组,这种写法完全没问题;如果数组可能被修改,方案1的缓存方式更稳妥。
内容的提问来源于stack exchange,提问作者Shamoon
相关产品推荐
相关产品推荐

