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

如何优化TypeScript异步包装函数with401Redirection的类型定义以移除@ts-expect-error

解决方案

核心修改思路:将原来的整体函数泛型拆分为参数列表、返回值类型两个独立泛型,让TS可以正确关联类型校验,无需再使用@ts-expect-error注解,同时可以保证所有被包装函数的参数、返回值类型正常自动推导。

修改后的with401Redirection定义如下:

const with401Redirection = <Args extends any[], R>(
  call: (...args: Args) => Promise<R>
): (...args: Args) => Promise<R> => {
  return async (...args: Args) => {
    try {
      return await call(...args);
    } catch (error) {
      if ((error as any).httpStatus === 401) {
        // 401场景自定义逻辑
      }
      throw error;
    }
  };
};

完整验证代码如下:

interface User {
  id: string;
  name: string;
}

interface ItemPayload {
  field1: string;
  field2: string;
}

interface ItemResponse {
  id: string;
  field1: string;
  field2: string;
}

const client = {
  get<ResponseType>(url: string): Promise<ResponseType> {
    // 服务端请求逻辑
    return '' as any;
  },
  post<ResponseType>(url: string, body: Record<string, any>): Promise<ResponseType> {
    // 服务端请求逻辑
    return '' as any;
  }
};

const getUser = with401Redirection(() =>
  client.get<User>('url_1')
);
// 自动推导类型:const getUser: () => Promise<User>

const saveItem = with401Redirection((body: ItemPayload) =>
  client.post<ItemResponse>('url_2', body)
);
// 自动推导类型:const saveItem: (body: ItemPayload) => Promise<ItemResponse>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 01:36:05