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

如何实现按请求方法动态控制参数可选性的TypeScript HTTP函数

类型安全HTTP请求函数的参数类型约束问题

我正尝试实现一个极简的类型安全函数,用于对接类型化服务端API发起HTTP请求,但在类型处理上遇到了困难。具体来说,需要让第三个参数(HTTP请求体)在GET和DELETE请求时为可选参数,而在POST和PUT请求时为必填参数并进行类型校验。

简化示例代码

export type Method = 'GET' | 'DELETE' | 'POST' | 'PUT'

// 尝试1:
const httpRequest1 = <M, D>(method: M, url: string, data?: D) =>
  'not implemented yet' as any


// 尝试2:
type HttpRequest <M extends Method, D, R=unknown> = M extends 'GET' | 'DELETE'
  ? (method: M, url: string) => Promise<R>
  : (method: M, url: string, data: D) => Promise<R>

const httpRequest2: HttpRequest = (method, url, data) =>
  'not implemented yet' as any


// 期望用法:
interface Data {
  title: string;
}
httpRequest<'POST', Data>('POST', '/', { title: 'test' }) // 应通过类型检查
httpRequest<'POST', Data>('POST', '/', { titleoops: 'test' }) // 不应通过类型检查
httpRequest<'POST', Data>('POST', '/') // 不应通过类型检查
httpRequest<'GET', undefined>('GET', '/') // 应通过类型检查

我始终无法让这四个条件同时按预期通过类型检查,至少有一个条件会失效。

补充说明:若想了解完整用例,可参考对应的类型化完整实现。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 06:24:51