I am currently working on defining flexible types for my api responses, but I am struggling to find the right approach for type conversion using TypeScript 4.5.4. My goal is to parse the response and determine the type that will be used later in the code. The response type is essential for proper typing before parsing.
TS Playground (EDIT: fixed id)
// this and ReviewResponse are specific to reviews
export type Review = {
id: number;
name: string;
rating: number;
review: string;
};
export type ReviewResponse = ResponseType<Review>;
// this is a general type placed elsewhere
export type ResponseType<Item> = {
id: number;
attributes: {
[key: string]: Item
}
}
// parser function to run after fetching the data
function parseResponse(data: ReviewResponse[]): Review[] {
return data.map((item) => {
return {
id: item.id,
...item.attributes,
};
});
}
Function parseResponse
has an error visible below.
Why TS doesn't understand that Item is of type Review, what am I missing?:
Type '{ id: number; }[]' is not assignable to type 'Review[]'.
Type '{ id: number; }' is missing the following properties from type 'Review': name, rating, review (2322)