如何为REST Countries API响应正确定义所需TypeScript类型?
解决方法
1. TypeScript类型处理
完全可以只定义你需要的类型,TypeScript的结构类型系统会自动忽略多余字段。不过要注意:REST Countries API返回的原始字段和你写的ICountry接口存在差异,比如name是包含common/official等属性的对象,capital是数组(部分国家有多个首都),国旗数据存在flags对象里,所以需要调整接口或做结构转换:
// 适配API结构的接口 interface ICountry { name: { common: string }; capital: string[]; flag: string; population: number; } // 请求数据并适配类型 async function fetchCountries() { const response = await fetch("https://restcountries.com/v3.1/all"); const rawCountries = await response.json(); // 提取所需字段并转换结构 const countries: ICountry[] = rawCountries.map(country => ({ name: country.name, capital: country.capital || [], flag: country.flags.svg, population: country.population })); return countries; }
即便API返回其他字段,TypeScript只会校验你定义的属性,多余内容会被自动忽略。
2. 请求时直接筛选字段
REST Countries API支持通过fields参数指定返回字段,能直接减少传输的数据量,无需前端额外过滤。比如你需要name、capital、flags、population,请求URL可改为:
https://restcountries.com/v3.1/all?fields=name,capital,flags,population
API会仅返回你指定的字段,之后再转换成自定义类型即可,效率更高。
内容的提问来源于stack exchange,提问作者dinocode
相关产品推荐
相关产品推荐

