React / TypeScript - 类型 '{ index:number}' 缺少类型"IList"中的以下属性:长度、弹出、推送、连接和 26 个



使用React,我定义了两个接口,ICard, IList:

ICard

interface ICard {
id: any;
text: string;
index?: number;
list?: number;
}

IList

interface IList extends Array<ICard> {
index?: number;
}

我想创建一个类型,它是illist的列表,我将在一个单独的组件中使用它,该组件位于illist之上并保存这个列表列表。我试图在setState中定义我的列表列表:

const [lists, setLists] = useState<IList[]>([{index: 0}]);

然而,我得到的错误是在标题中,如下所示:Type '{ index:number}' is missing the following properties from type 'IList': length, pop, push, concat我不确定解决方案是什么,因为我是TypeScript/JS的新手。如有任何帮助,不胜感激。

您正在扩展基本的Array类型,因此typescript期望IList具有数组的所有属性,当您期望它仅具有单个IList对象的属性时,再加上index。您可能想要创建一个扩展ICard类型的数组:

interface CardWithIndex extends ICard {
index?: number;
}
type IList = Array<CardWithIndex>

或者你可以直接声明状态变量的类型,就像@RohitKhanna说的:

const [lists, setLists] = useState<CardWithIndex[]>([{index: 0}]);

最新更新