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

如何为TypeScript封装的integratedFetch添加静态json方法?

给封装的fetch函数添加.json静态方法的解决方案

问题根源

你之前通过prototype添加json方法的方式错误,因为integratedFetch是函数对象,prototype属性仅服务于该函数作为构造函数创建的实例,而非函数本身。TypeScript报错的核心原因是原类型定义中未包含json方法的声明。

正确实现步骤

要给函数本身添加静态方法,需先扩展类型定义,再直接给函数对象挂载属性:

  1. 定义包含扩展方法的类型
    先声明主函数的基础类型,再通过接口继承扩展出包含json方法的完整类型:
// 主函数的基础类型
type IntegratedFetchFn = (
    input: RequestInfo,
    init?: RequestInit,
    options?: Partial<IntegratedFetchOptions>
) => Promise<Response>;

// 扩展出包含json方法的完整类型
interface IntegratedFetch extends IntegratedFetchFn {
    json: <T>(
        input: RequestInfo,
        init?: RequestInit,
        options?: Partial<IntegratedFetchOptions>
    ) => Promise<T>;
}
  1. 实现函数并挂载json方法
    将integratedFetch标注为IntegratedFetch类型,然后直接给函数对象添加json属性:
const integratedFetch: IntegratedFetch = (input, init, options) => {
    return fetch(input, init).then(async (response) => {
        const { status } = response;
        const responseClass = getResponseClass(response);
        if (responseClass) {
            switch (Number(responseClass) as ResponseClass) {
                case ResponseClass.Informational:
                    // 处理信息类响应逻辑
                case ResponseClass.Successful:
                    // 处理成功类响应逻辑
                default:
                    throw Error(`Response class ${responseClass} unrecognized`);
            }
        }
        return response;
    });
};

// 直接给函数对象挂载json方法
integratedFetch.json = <T>(input, init, options) =>
    integratedFetch(input, init, options).then(response => response.json() as Promise<T>);

验证期望用法

修改后即可按预期方式调用:

// 自动解析JSON的简化调用
integratedFetch.json<MyType>('/api/resource', { method: 'GET' });

// 保留原有的手动解析方式
integratedFetch('/api/resource').then(r => r.json() as Promise<MyType>);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 08:25:21