首页 > 解决方案 > 无法将 API 响应数据映射到 typescript 接口

问题描述

我正在使用一个返回对象列表的 API,然后我希望将其自动映射到 typescript 接口。

API 数据:https ://fakestoreapi.com/products

以前我使用过 PokemonAPI,它返回一个带有对象列表的对象(https://pokeapi.co/)。这个 API 到接口映射工作得很好,因为我的接口 PokemonData 匹配 api 响应。

当“fakestoreapi”的 API 响应返回一个列表时,如何让它自动映射?

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
        })
    }
}

}

标签: reactjstypescriptreduxreact-redux

解决方案


resData的不是 typePokemonData而是 type Pokemon[]


推荐阅读