Although I saw some other posts with people having the same issue, I didn't find any other case that's similar to mine.
I have this block of code where I need to split an object in 4 parts:
const eventsLastAddedLine1: EventsListType["events"] =
eventsLastadded &&
Object.entries(eventsLastadded?.data)
.slice(0, 4)
.map((entry) => entry[1]);
That code is working well but Typescript is warning this (about eventsLastAddedLine1) in VS Code:
Type 'unknown[]' is not assignable to type '{ id: number; attributes: { slug: string; name: string; startDate: Date; endDate: Date; }; }[]'.
If I leave the mouse over eventsLastAddedLine1 (to see its type definition), looks correct:
const eventsLastAddedLine1: {
id: number;
attributes: {
slug: string;
name: string;
startDate: Date;
endDate: Date;
};
}[]
My definition for EventsListType is the following:
export type EventsListType = {
events: { id: number; attributes: { slug: string; name: string; startDate: Date; endDate: Date } }[];
isReady: boolean;
};
I'm not a Typescript expert (still learning), so I can't find where is the problem. How can I fix it? Thank you!
EDIT:
This is where eventsLastadded comes from:
const { data: eventsLastadded } = useSWR(`/events?${queryLastAdded}`, swrFetcher);
The data above has the following type:
SWRResponse<any, any>.data?: any
Based on the type definition for useSWR hook, you can type cast the response to EventsListType["events"][] by passing it as a generic type parameter like this:
const { data: eventsLastadded } = useSWR<EventsListType["events"][]>(`/events?${queryLastAdded}`, swrFetcher);
// eventsLastadded is typecasted as EventsListType["events"][] | undefined