Vue项目使用vue-notification包报错:Property '$notify' does not exist on type
这个报错是TypeScript没有识别到vue-notification注入到Vue原型上的$notify方法导致的类型错误,运行时功能本身是正常的,只需要补全对应类型声明即可解决,按以下步骤操作:
步骤1:安装官方类型包
首先检查是否已经安装了对应的类型声明包,没有的话先执行安装:
npm install -D @types/vue-notification
安装完成后重启IDE的TypeScript服务,大部分情况下就能解决问题。
步骤2:手动补全类型声明(如果安装类型包后仍报错)
如果官方类型包没有生效,可以手动写类型扩展:
- 在项目
src目录下新建vue-notification.d.ts类型声明文件,写入以下内容:
import Vue from 'vue' declare module 'vue/types/vue' { interface Vue { $notify: (options: { title?: string text?: string type?: 'success' | 'warn' | 'error' | 'info' duration?: number speed?: number data?: any }) => void } }
- 检查项目根目录的
tsconfig.json,确保include配置包含了该声明文件,示例配置如下:
{ "include": [ "src/**/*.ts", "src/**/*.d.ts", "src/**/*.vue" ] }
临时规避方案
如果需要临时绕过类型校验,可以把调用写法改成:
(this as any).$notify({ title: 'Important message', text: 'Hello user!' })
该方案不推荐长期使用,仅作紧急调试用。
操作完成后重启IDE的TypeScript服务即可生效,VSCode用户可以按Ctrl+Shift+P(Mac为Command+Shift+P),选择「TypeScript: Restart TS Server」快速重启。
内容的提问来源于stack exchange,提问作者Layan
相关产品推荐
相关产品推荐

