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

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

问题


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

const { proxy } = getCurrentInstance();  

报错信息:

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你确信返回的实例是非空的。在这种情况下,你可以使用非空断言!:

const { proxy } = getCurrentInstance()!;

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

const instance = getCurrentInstance();
if (instance) {
  const { proxy } = instance;
  // 现在你可以安全地使用 proxy
} else {
  console.error("无法获取组件实例");
}
相关文章
|
9月前
|
容器
Echarts报错 Cant read property getWidth of null的解决方案
Echarts报错 Cant read property getWidth of null的解决方案
88 0
|
7月前
【已解决】TypeError: Cannot destructure property `createHash` of ‘undefined‘ or ‘null‘
【已解决】TypeError: Cannot destructure property `createHash` of ‘undefined‘ or ‘null‘
184 1
|
6月前
|
JavaScript API
【Vue】Cannot set reactive property on undefined,null,or primitive value:undefined
【Vue】Cannot set reactive property on undefined,null,or primitive value:undefined
94 0
|
3月前
|
Java
Error:(15, 13) java: No property named “id” exists in source parameter(s). Did you mean “null”?
Error:(15, 13) java: No property named “id” exists in source parameter(s). Did you mean “null”?
32 1
|
9月前
|
Java 数据库连接 mybatis
There is no getter for property named ‘null‘ in ‘class
There is no getter for property named ‘null‘ in ‘class
114 0
There is no getter for property named ‘null‘ in ‘class
|
11月前
|
Java
Error:(15, 13) java: No property named “id” exists in source parameter(s). Did you mean “null”?
Error:(15, 13) java: No property named “id” exists in source parameter(s). Did you mean “null”?
|
JavaScript
Uncaught TypeError: Cannot read property 'getItem' of null
Uncaught TypeError: Cannot read property 'getItem' of null
264 0
MapStruct - No property named “XXX“ exists in source parameter(s). Did you mean “null“?
MapStruct - No property named “XXX“ exists in source parameter(s). Did you mean “null“?
704 0
|
定位技术
调用百度报Cannot read property ‘lng‘ of null错误
调用百度报Cannot read property ‘lng‘ of null错误
调用百度报Cannot read property ‘lng‘ of null错误