如何通过index.d.ts让TypeScript识别vue.global.prod.js的全局Vue方法?
给全局Vue添加TypeScript类型支持的方案
完全可以通过自定义index.d.ts文件让TypeScript识别window.Vue上的所有方法,具体操作步骤如下:
创建或修改项目根目录下的
index.d.ts
直接扩展Window接口,复用Vue官方的全局类型定义是最省心的方式:import type { GlobalVue } from 'vue/global'; declare global { interface Window { Vue: GlobalVue; } } export {};GlobalVue类型已经包含了Vue全局模式下的所有API,不用手动逐个声明。按需手动声明特定API(可选)
如果你只需要TypeScript识别部分全局方法,也可以单独指定:declare global { interface Window { Vue: { createApp: typeof import('vue').createApp; ref: typeof import('vue').ref; reactive: typeof import('vue').reactive; // 按需添加其他需要的API }; } } export {};确保TypeScript能读取到声明文件
打开tsconfig.json,检查include数组是否包含index.d.ts,没有的话补充进去:{ "include": [ "src/**/*", "index.d.ts" ] }
完成以上操作后,TypeScript就能对window.Vue.createApp、window.Vue.ref这类全局调用提供完整的类型提示和校验了。
内容的提问来源于stack exchange,提问作者Donny
相关产品推荐
相关产品推荐

