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("无法获取组件实例");
}
相关推荐
Sunlightʊə12 小时前
2.登录页测试用例
运维·服务器·前端·功能测试·单元测试
Code Crafter13 小时前
ES6-ES14 新特性速查
前端·ecmascript·es6
Lhuu(重开版13 小时前
CSS从0到1
前端·css·tensorflow
不说别的就是很菜14 小时前
【前端面试】HTML篇
前端·html
前端一小卒14 小时前
生产环境Sourcemap策略:从苹果事故看前端构建安全架构设计
前端·javascript
im_AMBER15 小时前
React 18
前端·javascript·笔记·学习·react.js·前端框架
老前端的功夫15 小时前
Vue2中key的深度解析:Diff算法的性能优化之道
前端·javascript·vue.js·算法·性能优化
han_15 小时前
前端高频面试题之Vue(高级篇)
前端·vue.js·面试
不说别的就是很菜16 小时前
【前端面试】CSS篇
前端·css·面试
by__csdn16 小时前
nvm安装部分node版本后没有npm的问题(14及以下版本)
前端·npm·node.js