如何为导入的JavaScript变量指定类型?解决VS Code无类型推断问题
解决导入AxiosInstance无类型推断的问题
方法1:在导出文件中直接标注类型(推荐)
在导出service的文件里添加JSDoc类型注解,所有导入该变量的地方会自动获得类型推断:
// src/utils/service.js import axios from 'axios'; /** @type {import('axios').AxiosInstance} */ export const service = axios.create({ baseURL: process.env.BASE_URL, timeout: 1000 * 60 * 5, withCredentials: true, });
后续直接导入service时,VS Code会自动识别其类型。
方法2:在导入文件中手动指定类型
若无法修改导出文件,可通过重命名导入变量,再给新变量标注类型:
// 导入原始变量并改名 import { service as rawService } from '@/utils/service.js'; /** @type {import('axios').AxiosInstance} */ const service = rawService;
后续使用service时,VS Code会提供对应的类型提示。
方法3:使用类型声明文件(.d.ts)
如果项目支持TypeScript类型声明,可创建对应的.d.ts文件:
// src/utils/service.d.ts import type { AxiosInstance } from 'axios'; export declare const service: AxiosInstance;
保存后,VS Code会自动读取该声明文件,为导入的service提供类型推断。
内容的提问来源于stack exchange,提问作者Jam
相关产品推荐
相关产品推荐

