在 vue 3 + typescript 中为 app.config.globalproperties 添加类型支持,核心是通过模块合并扩展 componentcustomproperties 接口,声明 $http、$message、$filters 等属性类型,并确保挂载时类型一致,从而获得类型检查与自动补全。

在 Vue 3 + TypeScript 项目中,为 app.config.globalProperties 添加类型支持,核心是**扩展全局属性的类型定义**,让 TypeScript 能识别你在上面挂载的自定义属性(比如 $http、$message、$filters 等),避免类型报错和失去自动补全。
1. 在类型声明文件中扩展 ComponentCustomProperties
Vue 3 的类型系统通过 ComponentCustomProperties 接口来描述全局属性的类型。你需要在自己的 .d.ts 文件(如 src/global.d.ts 或 src/types/vue-shim.d.ts)中对其进行模块合并(module augmentation):
(注意:该文件需被 TypeScript 正确包含,通常放在 src/ 下即可,无需手动 import)
import 'vue'
declare module 'vue' {
export interface ComponentCustomProperties {
$http: typeof import('@/utils/request').default // 例如 axios 实例
$message: import('element-plus').ElMessage
$filters: {
formatDate: (date: string | number | Date, fmt?: string) => string
}
}
}
2. 挂载时确保类型一致
在 main.ts 中挂载全局属性时,TypeScript 会根据上述声明校验类型。如果类型不匹配(比如返回值或参数不符),TS 会报错,这正是你想要的类型安全:
- 挂载
$http时,确保它确实是 axios 实例或符合你声明的类型 - 挂载
$filters时,对象结构需与声明完全一致(方法名、参数、返回值) - 若使用 Composition API,
getCurrentInstance()?.proxy上的属性也会获得类型提示(但推荐优先用useXXX组合式函数替代)
3. 针对 setup() 和组合式 API 的补充说明
虽然 globalProperties 主要服务于 Options API,但在 setup() 中仍可能用到(尤其迁移老项目)。此时建议:
- 优先使用
provide / inject或自定义 Hook(如useHttp())替代直接访问this.$xxx - 若必须访问,可通过
getCurrentInstance()获取 proxy,并启用类型断言(但前提是已正确定义ComponentCustomProperties):
import { getCurrentInstance } from 'vue'
export default {
setup() {
const instance = getCurrentInstance()
if (instance) {
console.log(instance.proxy?.$http) // ✅ 有类型提示
}
}
}
4. 验证是否生效
重启 TypeScript 服务(或保存 .d.ts 文件后等待自动重载),然后在任意组件的 setup() 或 Options API 的 methods 中尝试输入 this.$,应能看到你声明的属性并获得完整类型推导和跳转支持。
如果没提示,检查:
– 文件是否以 .d.ts 结尾且位于 src/ 下
– tsconfig.json 中 include 是否覆盖该路径(默认 ["src/**/*"] 即可)
– 是否有语法错误导致声明未被加载
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











