返回

Vue.js 3 中“属性 'projects' 在类型 'CreateComponentPublicInstance' 上不存在”错误:原因和解决方案

vue.js

解决 Vue.js 3 中“属性 'projects' 在类型 'CreateComponentPublicInstance' 上不存在”错误

简介

在 Vue.js 3 中使用 computed 属性时,开发人员可能会遇到一个常见的 TypeScript 错误:“属性 'projects' 在类型 'CreateComponentPublicInstance' 上不存在”。此错误通常是由于 TypeScript 类型推断不准确造成的。本文将探讨导致此错误的原因并提供两种可行的解决方案。

错误原因

当在 shims-vue.d.ts 文件中添加对 Vuex 存储的类型声明时,TypeScript 会将 this 类型的推断从 Vue 实例更改为更通用的 CreateComponentPublicInstance 类型。这个通用类型没有声明 projects 属性,因此导致错误。

解决方案

有两种方法可以解决此问题:

方法 1:在 Vue 组件中明确声明类型

在 Vue 组件中使用类型注释明确 this 类型可以解决此问题。如下所示:

<script setup lang="ts">
const projects: Project[] = ref([]);
</script>

方法 2:更新 shims-vue.d.ts

另一种解决方法是更新 shims-vue.d.ts 文件,将 this 类型的 Vue 实例添加到 CreateComponentPublicInstance 类型中。如下所示:

// shims-vue.d.ts
import { ComponentCustomProperties } from 'vue'
import { Store } from 'vuex'
import { Vue } from 'vue/types/vue'

declare module '@vue/runtime-core' {
  // declare your own store states
  interface State {
    count: number
  }

  // provide typings for `this.$store`
  interface ComponentCustomProperties {
    $store: Store<State>
  }

  // Add Vue to the CreateComponentPublicInstance type
  interface CreateComponentPublicInstance<
    P = {},
    E extends EmitsOptions = EmitsOptions,
    M extends object = {},
    PropsOptions = PropsDefinition<P>,
    This = Vue
  > {
    // ... other properties
  }
}

其他建议

  • 确保 TypeScript 和 Vue 依赖项是最新的。
  • 重新启动开发服务器。
  • 检查 shims-vue.d.ts 文件是否存在其他错误。
  • 创建一个最小的可重现示例并将其发布到 GitHub 或其他代码托管平台。

常见问题解答

  1. 为什么 TypeScript 无法正确推断 this 类型?

TypeScript 会根据上下文推断 this 类型。当在 shims-vue.d.ts 中添加 Vuex 存储的类型声明时,TypeScript 会将 this 类型的推断更改为更通用的 CreateComponentPublicInstance 类型。

  1. 为什么在 Vue 组件中明确声明类型可以解决问题?

明确声明 this 类型可以覆盖 TypeScript 的类型推断并强制使用正确的类型。

  1. 是否可以只使用一种方法来解决问题?

是的,你只需要选择一种适合你的项目的方法。

  1. 我遇到其他 TypeScript 错误,该如何解决?

TypeScript 错误可能是由于各种原因造成的。请查看 TypeScript 文档或在网上搜索相关错误信息以了解解决方案。

  1. 如何防止此错误再次出现?

保持 TypeScript 和 Vue 依赖项的最新状态可以帮助防止此错误再次出现。还可以考虑使用类型检查器,例如 ESLint 或 TSLint,以检测 TypeScript 错误。