You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Typescript Interface如何定义适配含动态顶层键的API返回数据结构

解决方案

第一步:定义通用固定结构

先把不会随平台变化的内部结构抽出来单独定义,避免重复代码:

// 先定义单条游戏数据的结构,按需补充字段即可
interface GameItem {
  id: number;
  name: string;
  releaseDate: string;
  // 其他字段自行补充
}

// 每个平台下固定的data包裹结构
interface PlatformGameData {
  data: GameItem[];
}

第二步:定义动态顶层键的响应类型

分两种场景按需选择:

场景1:平台类型不固定,后续可能新增

用字符串索引签名即可,适配任意平台键名:

interface GameApiResponse {
  // 顶层键为任意平台字符串,值为固定的平台数据结构
  [platform: string]: PlatformGameData;
}

场景2:平台只有固定的枚举值(ps4/xbox/switch)

推荐用联合类型+泛型的写法,类型校验更严谨:

// 先定义所有支持的平台枚举
type Platform = 'ps4' | 'xbox' | 'switch';

// 泛型传入当前请求的平台,返回对应键名的响应类型
type GameApiResponse<T extends Platform> = {
  [P in T]: PlatformGameData;
}

使用示例:

// 请求ps4平台游戏时,直接指定泛型为'ps4'即可
const getPs4Games = async (): Promise<GameApiResponse<'ps4'>> => {
  const res = await fetch('/your/api/path?platform=ps4');
  return res.json();
}

这种写法下TS会精准识别返回结果的顶层键是你传入的平台值,不会出现多余的类型提示,也能避免写错键名的问题。

内容的提问来源于stack exchange,提问作者ACDev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 15:48:02