如何实现按请求方法动态控制参数可选性的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
相关产品推荐
相关产品推荐

