我正在使用一个返回对象列表的 API,然后我想将其自动映射到 typescript 接口(interface)。
API 数据:https://fakestoreapi.com/products
之前我使用过 PokemonAPI,它返回一个包含对象列表的对象 (https://pokeapi.co/)。这个 API 到接口(interface)映射工作得很好,因为我的接口(interface) 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
})
}
}
最佳答案
您的resData
不是PokemonData
类型,而是Pokemon[]
类型。
关于reactjs - 无法将 API 响应数据映射到 typescript 接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63233500/