解决TypeScript中useRef相关的‘No matches overload call’报错
解决TypeScript中
Array.from接收undefined的类型错误 问题原因
代码里navCurrent?.querySelectorAll('a')在navCurrent为null时会返回undefined,而Array.from要求参数必须是可迭代/类数组对象,undefined不满足该类型要求,因此触发TypeScript类型报错。
解决方案
方案1:用空值合并运算符提供默认值
通过??给querySelectorAll的结果兜底一个空数组,确保Array.from始终接收合法的可迭代对象:
const navRef = useRef<null | HTMLElement>(null); const setFocusables = () => { let navCurrent = navRef.current; menuFocusables = [ buttonRef.current, ...Array.from(navCurrent?.querySelectorAll('a') ?? []), ]; firstFocusableEl = menuFocusables[0]; lastFocusableEl = menuFocusables[menuFocusables.length - 1]; };
方案2:提前判断navCurrent是否有效
先检查navCurrent不为null,再执行querySelectorAll,从根源避免产生undefined:
const navRef = useRef<null | HTMLElement>(null); const setFocusables = () => { let navCurrent = navRef.current; menuFocusables = [buttonRef.current]; if (navCurrent) { menuFocusables.push(...Array.from(navCurrent.querySelectorAll('a'))); } firstFocusableEl = menuFocusables[0]; lastFocusableEl = menuFocusables[menuFocusables.length - 1]; };
方案3:用逻辑或运算符兜底默认值
和方案1逻辑类似,用||替代??,当querySelectorAll返回空NodeList或undefined时,都会替换为空数组:
const navRef = useRef<null | HTMLElement>(null); const setFocusables = () => { let navCurrent = navRef.current; menuFocusables = [ buttonRef.current, ...Array.from(navCurrent?.querySelectorAll('a') || []), ]; firstFocusableEl = menuFocusables[0]; lastFocusableEl = menuFocusables[menuFocusables.length - 1]; };
额外提示
建议给相关变量明确类型定义,避免后续类型问题:
let menuFocusables: (HTMLElement | null)[] = []; let firstFocusableEl: HTMLElement | null = null; let lastFocusableEl: HTMLElement | null = null;
内容的提问来源于stack exchange,提问作者realtimebyte
相关产品推荐
相关产品推荐

