TypeScript 中的 Nuxt/Vue.js:对象文字可能仅指定已知属性,但类型“VueClass"中不存在“组件" [英] Nuxt / Vue.js in TypeScript: Object literal may only specify known properties, but 'components' does not exist in type 'VueClass'

查看:200
本文介绍了TypeScript 中的 Nuxt/Vue.js:对象文字可能仅指定已知属性,但类型“VueClass"中不存在“组件"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm not quite sure why I'm getting this error message when I use a decorator with components and middleware:

经检查,错误如下:TS2345:类型参数'{ components: { Test: typeof Nav;};中间件:字符串[];}' 不能分配给 'VueClass' 类型的参数.对象字面量可能只指定已知属性,但组件"类型不存在于VueClass"类型中.你的意思是写'组件'吗?

没有中间件,@Component 装饰器不再大惊小怪:

Without middleware, the @Component decorator no longer fusses:

知道为什么会这样吗?

推荐答案

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

I see that middleware is a property defined by Nuxt and isn't a standard Vue property.

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

The error message is a little bit misleading - it looks like it's saying the problem is with the components property, but what it's actually saying is that an object with both {components: ..., middleware: ...} doesn't match any of the expected types.

解决办法:

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

What you need to do is update the definition of the Vue ComponentOptions type to add the middleware property.

为此,创建一个新的 .d.ts 文件(或编辑现有的类型文件,例如 references.d.ts)并向其添加以下声明:

To do this, create a new .d.ts file (or edit an existing type file e.g. references.d.ts) and add this declaration to it:

// 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[];
  }
}

这只是 Vuex 插件如何将 store 属性添加到 Vue 组件类型的变体.请参阅vuex/types/vue.d.ts source) 了解这是如何完成的.

This is just a variation on how the Vuex plugin adds the store property to the Vue component type. See the vuex/types/vue.d.ts source) for how this is done.

这篇关于TypeScript 中的 Nuxt/Vue.js:对象文字可能仅指定已知属性,但类型“VueClass"中不存在“组件"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆