首页
/ 解决@hey-api/openapi-ts生成文件中的TypeScript错误问题

解决@hey-api/openapi-ts生成文件中的TypeScript错误问题

2025-07-01 15:56:09作者:翟江哲Frasier

在使用@hey-api/openapi-ts生成TypeScript客户端代码时,开发者可能会遇到"Property 'client' does not exist on type"的错误。这个问题通常与版本更新和配置变更有关,下面我们将详细分析问题原因并提供解决方案。

问题现象

当使用@hey-api/openapi-ts生成客户端代码后,在调用生成的API方法时,TypeScript编译器会报错,提示"Property 'client' does not exist on type"的错误。错误通常出现在类似下面的代码中:

export const getCurrentUser = <ThrowOnError extends boolean = false>(
  options?: Options<GetCurrentUserData, ThrowOnError>
) => {
  return (options?.client ?? client).get<GetCurrentUserResponse, unknown, ThrowOnError>({
    security: [
      {
        scheme: 'bearer',
        type: 'http'
      }
    ],
    url: '/api/auth/users/me',
    ...options
  });
};

问题原因分析

这个错误通常由以下几个原因导致:

  1. 版本不匹配:使用的@hey-api/openapi-ts和相关客户端库版本不一致或过时
  2. 配置缺失:在新版本中,配置方式发生了变化,缺少必要的配置项
  3. 客户端初始化问题:生成的客户端代码与实际的HTTP客户端实现不兼容

解决方案

1. 更新到最新版本

首先确保所有相关包都更新到最新版本:

{
  "@hey-api/openapi-ts": "^0.64.5",
  "@hey-api/client-axios": "^0.6.1",
  "@hey-api/client-fetch": "^0.8.1"
}

2. 正确配置生成器

在新版本中,配置方式有所变化,需要明确指定使用的HTTP客户端和SDK生成选项。创建一个openapi-ts.config.ts文件:

import { defaultPlugins } from '@hey-api/openapi-ts';

export default {
  input: 'path/to/openapi.json',
  output: 'src/client',
  plugins: [
    ...defaultPlugins,
    '@hey-api/client-fetch', // 或 '@hey-api/client-axios'
    {
      name: '@hey-api/sdk',
      asClass: false
    }
  ]
};

3. 客户端初始化

在应用入口文件中正确初始化客户端:

import { client } from '@/client/sdk.gen';
import axios from 'axios';

// 配置基础URL和认证信息
client.setConfig({
  baseURL: import.meta.env.VITE_API_URL,
  auth: () => getAuthToken() ?? ''
});

// 添加响应拦截器
client.instance.interceptors.response.use(
  response => response,
  error => {
    if (axios.isAxiosError(error) && error.response?.status === 401) {
      clearAuthToken();
      if (!window.location.pathname.startsWith('/login')) {
        window.location.href = '/login';
      }
      return Promise.reject(new Error('Session expired'));
    }
    return Promise.reject(error);
  }
);

注意事项

  1. 确保在生成客户端代码前已安装所有必要的依赖
  2. 如果从旧版本迁移,需要仔细阅读迁移指南,了解配置方式的变化
  3. 生成客户端代码后,检查生成的类型定义是否正确
  4. 如果使用axios客户端,确保axios已安装并配置正确

通过以上步骤,应该能够解决TypeScript错误问题,并正确使用生成的API客户端代码。如果问题仍然存在,可以检查生成的代码与HTTP客户端实现的兼容性,或者考虑使用不同的HTTP客户端实现。

登录后查看全文
热门项目推荐
相关项目推荐