Property ‘proxy‘ does not exist on type ‘ComponentInternalInstance | null‘.ts

问题

Vue 3 使用 getCurrentInstance 获取当前正在执行的组件实例 TypeScript 报错。

typescript 复制代码
const { proxy } = getCurrentInstance();  

报错信息:

typescript 复制代码
Property 'proxy' does not exist on type 'ComponentInternalInstance | null'.ts

解决方案

在Vue 3的Composition API中,getCurrentInstance()返回的类型是ComponentInternalInstance | null。因此,当你使用const { proxy } = getCurrentInstance();时,TypeScript会报错,因为proxy属性在类型定义中并不存在。

为了解决这个问题,你可以使用类型断言(Type Assertion)来告诉TypeScript你确信返回的实例是非空的。在这种情况下,你可以使用非空断言!:

typescript 复制代码
const { proxy } = getCurrentInstance()!;

请注意,使用非空断言表示你确信getCurrentInstance()永远不会返回null。如果你不能确保这一点,最好在代码中进行适当的空值检查。例如:

typescript 复制代码
const instance = getCurrentInstance();

if (instance) {
  const { proxy } = instance;
  // 现在你可以安全地使用 proxy
} else {
  console.error("无法获取组件实例");
}
相关推荐
葱头的故事1 小时前
vant van-uploader上传file文件;回显时使用imageId拼接路径
前端·1024程序员节
Mintopia1 小时前
🇨🇳 Next.js 在国内场景下的使用分析与实践指南
前端·后端·全栈
Mintopia2 小时前
深度伪造检测技术在 WebAIGC 场景中的应用现状
前端·javascript·aigc
BUG_Jia2 小时前
如何用 HTML 生成 PC 端软件
前端·javascript·html·桌面应用·1024程序员节
木易 士心2 小时前
CSS 样式用法大全
前端·css·1024程序员节
012925202 小时前
1.1 笔记 html 基础 初认识
前端·笔记·html
2501_929382652 小时前
[Switch大气层]纯净版+特斯拉版 20.5.0大气层1.9.5心悦整合包 固件 工具 插件 前端等资源合集
前端·游戏·switch·1024程序员节·单机游戏
非凡ghost2 小时前
Tenorshare 4DDiG(数据恢复软件) 最新版
前端·javascript·后端
非凡ghost2 小时前
WinMute(自动锁屏静音软件) 中文绿色版
前端·javascript·后端