TypeScript中的Nuxt/Vue.js:对象文字只能指定已知属性,但'VueClass'类型中不存在'components'

iRy*_*ell 2 typescript vue.js nuxt.js

当我使用带有组件和中间件的装饰器时,我不太确定为什么我收到此错误消息:

在此输入图像描述

经检查,错误如下: TS2345: Argument of type '{ components: { Test: typeof Nav; }; middleware: string[]; }' is not assignable to parameter of type 'VueClass'. Object literal may only specify known properties, but 'components' does not exist in type 'VueClass'. Did you mean to write 'component'?

在此输入图像描述

没有中间件,@ Component装饰器不再融合:

在此输入图像描述

知道为什么会这样吗?

Sly*_*nal 7

我看到这middleware是一个由Nuxt定义的属性,不是标准的Vue属性.

错误消息有点误导 - 看起来它说问题是components属性,但它实际上说的是两个 对象{components: ..., middleware: ...}都不匹配任何预期的类型.

解决方案:

您需要做的是更新Vue ComponentOptions类型的定义以添加middleware属性.

要执行此操作,请创建一个新.d.ts文件(或编辑现有类型文件,例如references.d.ts)并将此声明添加到其中:

// references.d.ts
/**
 * Extends interfaces in Vue.js
 */

import Vue, { ComponentOptions } from "vue";

declare module "vue/types/options" {
  interface ComponentOptions<V extends Vue> {
    // This adds the `middleware` property to the existing `vue/types/options/ComponentOptions` type
    middleware?: string | string[];
  }
}
Run Code Online (Sandbox Code Playgroud)

这只是Vuex插件如何将store属性添加到Vue组件类型的变体.查看vuex/types/vue.d.ts源代码)了解如何完成此操作.