简体   繁体   中英

React / TypeScript - Type '{ index:number}' is missing the following properties from type 'IList': length, pop, push, concat, and 26 more

Using React, and I have defined two interfaces, ICard, IList:

ICard

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

IList

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

I want to create a type which is a list of IList, which I will use in a separate component that sites above IList and holds this list of lists. I have tried to define my list of lists in a setState as:

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

however the error that I am getting is in the title and is as follows: Type '{ index:number}' is missing the following properties from type 'IList': length, pop, push, concat I am unsure what the solution is as I am new to TypeScript / JS. Any help would be appreciated.

You are extending the basic Array type, so typescript expects an IList to have all the properties of an array, when you're expecting it to simply have the properties of a single IList object, plus the index . You probably want to create an array of extended ICard types:

interface CardWithIndex extends ICard {
    index?: number;
}

type IList = Array<CardWithIndex>

Or you can just declare what type you expect the state variable to be, as @RohitKhanna said:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM