TypeScript中never类型能否替代any用于泛型?
问题解答
不能直接用never替代any作为泛型默认值,两者语义完全不匹配,强行替换会导致代码无法正常使用。
为什么never不适合?
never类型表示**“永远不可能存在的类型”**,比如:
- 永远不会返回的函数的返回值类型(比如抛出错误或死循环的函数)
- 变量被穷尽式类型检查后不可能存在的类型
而你的场景中,泛型T和D是用来指代响应数据和请求数据的类型,默认值的语义是“暂时不知道具体类型,允许任意类型”,这和never的语义完全矛盾。如果把默认值改成never,调用接口时默认情况下会要求响应数据必须是never类型(也就是不可能有值),这显然不符合实际业务需求。
正确的解决方案
针对你的场景,推荐以下两种方案:
1. 用unknown替代any(推荐)
unknown是TypeScript提供的类型安全的“未知类型”,它和any一样可以表示任意类型,但使用unknown类型的值时必须先进行类型检查或断言,避免了any带来的类型不安全问题,同时能满足ESLint的规则要求。
修改后的代码:
import axios, { AxiosRequestConfig, AxiosInstance, AxiosResponse } from 'axios'; import { stringify } from 'qs'; import { FilterParams } from '@src/interfaces/services/type'; // 用unknown替代any作为泛型默认值 type MethodType = <T = unknown, R = AxiosResponse<T>, D = unknown>( url: string, data?: D, config?: AxiosRequestConfig<D>, ) => Promise<R>; class AxiosClient { options: AxiosRequestConfig; client: AxiosInstance; get: MethodType; post: MethodType; patch: MethodType; delete: MethodType; constructor() { this.options = { baseURL: process.env.API_ROOT || '/api/', withCredentials: true, paramsSerializer: (params: FilterParams) => stringify(params, { arrayFormat: 'repeat' }), }; this.client = axios.create(this.options); this.get = this.client.get; this.post = this.client.post; this.patch = this.client.patch; this.delete = this.client.delete; } } export default new AxiosClient();
2. 定义业务通用类型作为默认值
如果你的后端接口有统一的响应格式(比如包含code、message、data字段),可以定义一个基础响应类型作为泛型默认值,这样更贴合业务场景:
// 定义通用响应格式 interface ApiResponse<T = unknown> { code: number; message: string; data: T; } // 修改泛型默认值为ApiResponse type MethodType = <T = ApiResponse, R = AxiosResponse<T>, D = unknown>( url: string, data?: D, config?: AxiosRequestConfig<D>, ) => Promise<R>;
3. 临时禁用ESLint规则(不推荐)
如果确实需要保留any(比如兼容老代码),可以通过注释禁用特定行的ESLint规则:
// eslint-disable-next-line @typescript-eslint/no-explicit-any type MethodType = <T = any, R = AxiosResponse<T>, D = any>( url: string, data?: D | undefined, config?: AxiosRequestConfig<D>, ) => Promise<R>;
关于ESLint的建议
ESLint建议用never替代any可能是规则的误判——泛型默认值场景下,never的语义并不适用。你可以根据实际业务场景选择上述合适的方案,无需强行遵循这个建议。
内容的提问来源于stack exchange,提问作者yjlee
相关产品推荐
相关产品推荐

