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("无法获取组件实例");
}
相关推荐
风止何安啊15 分钟前
从 “牵线木偶” 到 “独立个体”:JS 拷贝的爱恨情仇(浅拷贝 VS 深拷贝)
前端·javascript·面试
漫天黄叶远飞17 分钟前
地址与地基:在 JavaScript 的堆栈迷宫里,重新理解“复制”的哲学
前端·javascript·面试
小书包酱20 分钟前
告别在 vue 中使用公共 less 文件没有提示信息的烦恼
css·vue.js·less
杨啸_新房客21 分钟前
如何优雅的设置公司的NPM源
前端·npm
ohyeah22 分钟前
深入理解 JavaScript 中的继承与 instanceof 原理
前端·javascript
linhuai22 分钟前
flutter如何实现有登陆权限管理
前端
crary,记忆24 分钟前
React 之 useEffect
前端·javascript·学习·react.js
BD_Marathon32 分钟前
【JavaWeb】HTML常见标签——标题段落和换行
前端·html
小飞侠在吗34 分钟前
vue OptionsAPI与CompositionAPI
前端·javascript·vue.js
天涯路s1 小时前
qt怎么将模块注册成插件
java·服务器·前端·qt