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

如何优化TypeScript的API方法调用存储类型以实现自动同步?

自动同步API接口与Actionables类型的解决方案

核心思路

利用TypeScript的映射类型,将API接口的所有方法自动映射为对应的GenericActionables类型,实现新增API方法时Actionables自动同步,同时保留参数校验的类型安全。

代码实现示例

1. 原有定义(保留)

// 业务API接口
interface API {
  getUser: (id: number) => Promise<{ name: string; age: number }>;
  updateUser: (id: number, data: { name?: string; age?: number }) => Promise<boolean>;
}

// 通用Actionables泛型(保留参数校验能力)
type GenericActionables<T extends (...args: any[]) => any> = {
  action: T;
  validateParams?: (args: Parameters<T>) => boolean;
};

2. 优化后的自动同步类型

// 自动映射API方法的Actionables类型
type Actionables<T extends Record<string, (...args: any[]) => any>> = {
  [K in keyof T]: GenericActionables<T[K]>;
};

// 基于API接口自动生成对应的Actionables类型
type APIActionables = Actionables<API>;

3. 使用示例(自动校验与同步)

// 创建实例时,TypeScript会自动校验每个属性的类型
// 新增API接口方法后,APIActionables会自动包含对应的属性,无需手动更新
const actionables: APIActionables = {
  getUser: {
    action: async (id) => {
      // 业务逻辑实现
      return { name: 'John', age: 30 };
    },
    validateParams: (args) => typeof args[0] === 'number'
  },
  updateUser: {
    action: async (id, data) => {
      // 业务逻辑实现
      return true;
    },
    validateParams: (args) => typeof args[0] === 'number' && typeof args[1] === 'object'
  }
};

优化效果

  • 自动同步:新增API接口的方法后,APIActionables会自动生成对应方法的GenericActionables类型,无需手动修改Actionables定义
  • 类型安全:validateParams的参数类型会自动匹配对应API方法的参数,确保校验逻辑的正确性
  • 减少维护:避免手动逐个添加API方法对应的Actionables,降低出错概率

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 15:57:18