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

如何为第三方API的SDK/封装器定义TypeScript类型及存放位置

TypeScript SDK 类型定义组织方案

先明确你的疑问

你的场景不属于“为JS模块编写类型定义”的范畴,完全不需要自己手写.d.ts文件——.d.ts主要用于给纯JavaScript项目/库补充类型,而你是用TypeScript原生开发SDK,直接用.ts文件管理类型才是正确的方式。

具体实现建议

1. 按API模块拆分类型文件

创建专门的types目录,按API功能分组存放类型定义,比如:

  • types/account.ts:存放/accountInfo接口相关的所有类型
  • types/payment.ts:存放支付相关接口的类型
  • types/common.ts:存放多个API共用的通用类型(比如分页结构、基础用户信息)

这种拆分方式能避免单个文件过于臃肿,也方便后续维护。

2. 用ES模块导出/导入类型,抛弃命名空间

现代TypeScript开发中,命名空间已经被ES模块(export/import)取代,更符合TS的模块系统规范,也不会出现导入失败的问题。

示例代码(types/account.ts):

// 先定义嵌套的子类型
export interface AccountContact {
  phone: string;
  email: string;
  address: string;
}

export interface AccountOrderItem {
  orderId: string;
  amount: number;
  createTime: string;
}

// 再组合成顶层的接口返回类型
export interface AccountInfo {
  userId: string;
  username: string;
  contact: AccountContact;
  orderHistory: AccountOrderItem[];
  // 剩余30+属性依次定义...
}

在调用接口的业务代码中直接导入:

import { AccountInfo } from '../types/account';

async function getAccountInfo(): Promise<AccountInfo> {
  const res = await fetch('/accountInfo');
  return res.json();
}

3. 统一类型入口(可选)

如果觉得分散导入麻烦,可以在types/index.ts中做统一导出:

// types/index.ts
export * from './account';
export * from './payment';
export * from './common';

之后就能通过单个路径导入所有类型:

import { AccountInfo, PaymentRecord } from '../types';

4. 复杂类型的维护技巧

  • 把高频复用的子类型(比如通用的分页结构Pagination<T>)提取到types/common.ts中,避免重复定义
  • 对于属性极多的接口,可以按逻辑分组注释,提升可读性:
    export interface AccountInfo {
      // 基础用户信息
      userId: string;
      username: string;
      avatar: string;
    
      // 联系信息
      contact: AccountContact;
    
      // 订单相关
      orderHistory: AccountOrderItem[];
      totalSpent: number;
    
      // 其他系统信息
      createTime: string;
      lastLoginTime: string;
      // ...
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 13:50:23