如何为第三方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
相关产品推荐
相关产品推荐

