如何解决UseRef的current属性出现的TS2322类型错误?
解决useRef current属性的TS类型错误
错误原因
当你用useRef([])初始化时,TypeScript会自动推断该ref的类型为never[](空数组无明确元素类型时的默认推断),后续给current赋值({id:string, label:string})[]类型的数组,就会触发类型不兼容的错误。
另外注意你代码里的一个小问题:idnList.push(...)是错误写法,应该操作idnList.current.push(...),因为useRef的实际值存在current属性中。
解决方案
给useRef显式指定泛型类型,明确current的预期类型:
- 定义类型别名提升可读性,再初始化ref:
type IdnItem = { id: string; label: string }; const idnList = useRef<IdnItem[]>([]); const _idnList: IdnItem[] = []; if (_defaultIdn) { idnList.current.push({id:"id",label:"label"}) } idnList.current = _idnList;
- 若不需要初始空数组,可使用联合类型允许
undefined:
type IdnItem = { id: string; label: string }; const idnList = useRef<IdnItem[] | undefined>(undefined); const _idnList: IdnItem[] = []; if (_defaultIdn) { idnList.current?.push({id:"id",label:"label"}) } idnList.current = _idnList;
核心思路是通过泛型给useRef指定明确类型,避免TypeScript自动推断出never[]这种受限类型。
内容的提问来源于stack exchange,提问作者Younge
相关产品推荐
相关产品推荐

