typescript - 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
}
解决方案
使用 Nuxt Typescript 进行类型检查有一些奇怪的行为,因为它无法正确推断所有类型。这通过使用 Vuex vanilla 和辅助函数进一步复杂化。
要以最少的样板获取完整的类型信息,最好使用vue-class-component和vue-property-decorator,如Nuxt Typescript 文档 - 组件(请参阅类 API)中所示,以及基于类的vuex-module-decorators请参阅Nuxt Typescript 文档 - 存储。
但是,要在仍然使用 Options API 的同时回答解决此问题的原始问题 - 您必须在computed
and中声明所有函数的返回类型methods
;并根据需要强制 Vuex 辅助函数。
不幸的是,我们仍然没有得到正确的类型检查,asyncData
所以我们必须复制我们的代码data
和asyncData
函数。
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'
推荐阅读
- angular - Angular ng 服务命令
- android - 来自同一应用程序的 Firebase (FCM) 分组通知点击
- javascript - 我们可以从 Web 应用程序的前端进行缩小吗?
- eclipse - Eclipse 和 Visual Studio Code 中的量角器自动内容问题
- python - cx_Freeze 的熊猫分析问题
- bash - 从给定日期计算日期
- ruby-on-rails - 使用设计实现两因素身份验证
- oracle - 我怎样才能找到所有没有参考的表
- devexpress - DevExpress XAF:获取子集合的集合
- html - 将绝对定位的 DIV 与 IE11 中 TD 元素内的左值垂直对齐