Trouble mapping API response data to typescript interface

Viewed 1429

I am using an API which returns a list of objects, which I then want to be automaticly mapped to typescript interfaces.

API Data: https://fakestoreapi.com/products

Previously I have used the PokemonAPI, which returns an object with a list of objects (https://pokeapi.co/). This API to interface mapping works perfectly fine because my interface PokemonData matches the api response.

How can I get it to map automaticly when the API response from "fakestoreapi" returns a list?

export interface Pokemon {
id: number,
title: string,
price: number,
description: string,
category: string,
image: string }

export interface PokemonData {
results: Pokemon[]}


//reducer
case GET_POKEMON:
        return {
            data: action.payload,
            loading: false,
            error: ''
        }
//action
export const getPokemon = (pokemon: string): ThunkAction<void, RootState, null, PokemonAction> => {
return async dispatch => {
    try {
        const res = await fetch('https://fakestoreapi.com/products')

        if (!res.ok) {
            const resData: PokemonError = await res.json()
            throw new Error(resData.message)
        }

        const resData: PokemonData = await res.json()
        dispatch({
            type: GET_POKEMON,
            payload: resData
        })
    }catch(err){
        dispatch({
            type: SET_ERROR,
            payload: err.message
        })
    }
}

}

1 Answers

Your resData is not of type PokemonData but of type Pokemon[].

Related