You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决UseRef的current属性出现的TS2322类型错误?

解决useRef current属性的TS类型错误

错误原因

当你用useRef([])初始化时,TypeScript会自动推断该ref的类型为never[](空数组无明确元素类型时的默认推断),后续给current赋值({id:string, label:string})[]类型的数组,就会触发类型不兼容的错误。

另外注意你代码里的一个小问题:idnList.push(...)是错误写法,应该操作idnList.current.push(...),因为useRef的实际值存在current属性中。

解决方案

给useRef显式指定泛型类型,明确current的预期类型:

  1. 定义类型别名提升可读性,再初始化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;
  1. 若不需要初始空数组,可使用联合类型允许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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 23:54:05