
在 React 中,当你使用 useState
钩子来管理状态时,TypeScript 会尝试推断你的状态变量的类型。在你的例子中,listchannel
被初始化为一个空数组,因此 TypeScript 推断出 listchannel
的类型是 never[]
,即一个空数组类型。
由于 never[]
类型的数组没有任何属性,所以当你尝试访问 listchannel[1].value
时,TypeScript 会报错,因为 never
类型上不存在任何属性。
要解决这个问题,你需要明确地告诉 TypeScript listchannel
数组中元素的类型。你可以定义一个接口来描述这些对象,然后将这个接口作为 useState
的泛型参数。
解决办法
//给这个数组定义类型
interface Channel {
value: number;
label: string;
}
const [listchannel, setListchannel] = useState<Channel []>([]);
useEffect(() => {
async function getListchannel() {
const res = await Listchannel();
const res1 = res.data.channels.map((item:any) => {
return { value: item.id, label: item.name };
});
setListchannel(res1);
}
getListchannel();
}, []);
