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("无法获取组件实例");
}
相关推荐
RDCJM4 分钟前
SpringBoot + vue 管理系统
vue.js·spring boot·后端
angerdream6 分钟前
最新版vue3+TypeScript开发入门到实战教程之toRefs与toRef实用技巧
javascript·vue.js
有意义8 分钟前
极简的React 实现一
前端·javascript·react.js
小曹要微笑11 分钟前
委托(Delegate)在C#中的概念与应用
前端·javascript·c#
GISer_Jing15 分钟前
前端职业发展进阶指南:从技术深耕到能力破界,向资深工程师稳步迈进
前端·javascript·架构·typescript
weiwx8316 分钟前
【前端】Node.js使用教程
前端·node.js·vim
K姐研究社16 分钟前
Nano Banana 2 国内使用教程:LiblibAI 免翻墙使用
前端·javascript·html
松小白song26 分钟前
机器人路径规划算法之Dijkstra算法详解+MATLAB代码实现
前端·javascript·算法
SuperEugene27 分钟前
Vue3 中后台实战:VXE Table 从基础表格到复杂业务表格全攻略 | Vue生态精选篇
前端·vue.js·状态模式·vue3·vxetable
打小就很皮...30 分钟前
实现可交互的泳道图组件(React)
前端·react.js·泳道图