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

如何定义可省略未使用属性的TypeScript IAPIRequest抽象类型?

TypeScript API请求接口优化方案

要解决这个问题,核心是让接口仅在泛型参数非undefined时才声明对应必选属性,而非强制所有属性存在或设为可选。可以通过条件映射类型实现:

type IAPIRequest<B = undefined, P = undefined, Q = undefined> = 
  (B extends undefined ? {} : { body: B }) &
  (P extends undefined ? {} : { params: P }) &
  (Q extends undefined ? {} : { query: Q });

使用示例

  • 登录请求(仅需body):
type ILoginRequest = IAPIRequest<{ email: string; password: string }, undefined, undefined>;
// 实际类型:{ body: { email: string; password: string } }
  • 获取用户请求(需params和query):
type IGetUserRequest = IAPIRequest<undefined, { userId: string }, { includePosts: boolean }>;
// 实际类型:{ params: { userId: string }; query: { includePosts: boolean } }
  • 全属性请求:
type IUpdateUserRequest = IAPIRequest<{ name: string }, { userId: string }, { skipValidation: boolean }>;
// 实际类型:{ body: { name: string }; params: { userId: string }; query: { skipValidation: boolean } }

方案优势

  • 无冗余属性:泛型参数为undefined时,对应属性直接从类型中消失,无需手动传入undefined值。
  • 类型安全:存在的属性均为必选,且类型严格匹配泛型参数,不会出现“属性可能为undefined”的错误提示。
  • 灵活适配场景:可根据API请求的实际结构,自由组合body/params/query的存在与否。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 01:45:06