首页 > 解决方案 > Nuxt.js Typescript - 尝试访问计算属性中的数据对象时出错

问题描述

我正在使用选项 api,当尝试访问计算属性中的 Vue 数据对象的属性时,我在类型检查中遇到错误。

Property 'quantity' does not exist on type 'CombinedVueInstance<Vue, unknown, unknown, { item: unknown; total: unknown; menuItemCategories: any; }, Readonly<Record<never, any>>>'

该属性确实存在,因为页面能够使用计算属性正确加载和显示呈现的模板 - 只有类型检查器会抱怨。

组件代码(长度简化):

import Vue from "vue";
export default Vue.extend({
  data() {
    quantity: 1,
  },

  computed: {
    total() {
      return this.item.price * this.quantity;
    }
  },
});

编辑

data通过将属性用作对象,我已经能够解决这个问题。

不过,这确实会产生一些问题,因为最好将其data用作返回对象的函数。同样的问题适用于asyncData.

进一步的试验和错误表明我能够data通过属性访问函数属性methods。但是,如果我使用mapGetters来自 vuex 的助手,它会抛出与计算属性相同的类型错误。

在计算属性内的类型中methods也不可用。CombinedVueInstance

tsconfig.json

// tsconfig.json
{
  "compilerOptions": {
    "target": "es2018",
    "module": "esnext",
    "moduleResolution": "node",
    "lib": [
      "esnext",
      "esnext.asynciterable",
      "dom"
    ],
    "esModuleInterop": true,
    "allowJs": true,
    "sourceMap": true,
    "strict": true,
    "noEmit": true,
    "baseUrl": "./src",
    "paths": {
      "~/*": [
        "./*"
      ],
      "@/*": [
        "./*"
      ]
    },
    "types": [
      "@types/node",
      "@nuxt/types",
      "@nuxtjs/axios"
    ]
  },
  "exclude": [
    "node_modules"
  ]
}

vue-shim.d.ts

declare module "*.vue" {
  import Vue from 'vue'
  export default Vue
}

标签: typescriptvue.jsvue-componentnuxt.js

解决方案


使用 Nuxt Typescript 进行类型检查有一些奇怪的行为,因为它无法正确推断所有类型。这通过使用 Vuex vanilla 和辅助函数进一步复杂化。

要以最少的样板获取完整的类型信息,最好使用vue-class-componentvue-property-decorator,如Nuxt Typescript 文档 - 组件(请参阅类 API)中所示,以及基于类的vuex-module-decorators请参阅Nuxt Typescript 文档 - 存储

但是,要在仍然使用 Options API 的同时回答解决此问题的原始问题 - 您必须在computedand中声明所有函数的返回类型methods;并根据需要强制 Vuex 辅助函数。

不幸的是,我们仍然没有得到正确的类型检查,asyncData所以我们必须复制我们的代码dataasyncData函数。

import Vue from "vue";
import { mapGetters } from "vuex";

export default Vue.extend({
  // Default component data - supports type checking
  data() {
    return {
      quantity: 1,
    }
  },

  // Actual component data - sourced from api
  async asyncData() {
    const theAwaitedQuantity = // ... some await methods and promises from a backend api
    return {
      quantity: theAwaitedQuantity,
    }
  },

  computed: {
    ...mapGetters(["item"]),

    total(): number {
      // mapped properties from helper functions must have their types coerced.
      return (this.item as ItemType).price * this.quantity;
    }
  },

  methods: {
    someMethod(): string {
      return "methods also need their return type defined";
    }
  }
});

另请参阅此相关问题: “CombinedVueInstance<Vue, {}, {}, {}, Readonly<Record<never, any>>> 类型上不存在属性 'XXX'


推荐阅读