微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在Vue Router v4中为自定义元字段声明TypeScript类型接口?

如何解决如何在Vue Router v4中为自定义元字段声明TypeScript类型接口?

在当前为in beta.11 in vue-router-next repo Vue Router版本4 中,有一个documentation page关于如何使用TypeScript定义元字段自定义类型接口 >。

declare module 'vue-router' {
  interface RouteMeta {
    // is optional
    isAdmin?: boolean
    // must be declared by every route
    requiresAuth: boolean
  }
}

将沿着Vue垫片模块声明放置。我的看起来像:

declare module '*.vue' {
  import { defineComponent } from 'vue';

  const component: ReturnType<typeof defineComponent>;
  export default component;
}

declare module 'vue-router' {
  interface RouteMeta {
    isPublic?: boolean;
  }
}

但是,这不起作用。取而代之的是,这种定义接口的方式似乎会覆盖软件包随附的接口,或者声明“ vue-router”模块似乎可以做到这一点。

定义自定义元字段类型的正确方法是什么?

解决方法

他们的文档有误或充其量是不完整的。

Module Augmentation使用与Ambient Module声明相同的语法,并且仅在模块文件本身内时才被视为扩充。根据ECMAScript规范,模块定义为包含一个或多个顶级importexport语句的文件。

不是模块的文件中的代码片段完全符合您 的注意。它代替'vue-router'包的任何其他类型,而不是增加它们。但是我们想增加该程序包的类型,而不是替换它们。

但是,打算用作声明而非扩展的declare module语句必须位于文件中,而该文件不是模块。也就是说,在文件 中包含任何顶级importexport语句。

要解决此问题,请将declare module 'vue-router' {...}移动到一个单独的文件(例如augmentations.d.ts),并以export {}开头将该文件作为模块。

// augmenations.d.ts

// Ensure this file is parsed as a module regardless of dependencies.
export {}

declare module 'vue-router' {
  interface RouteMeta {
    // is optional
    isAdmin?: boolean
    // must be declared by every route
    requiresAuth: boolean
  }
}

现在让我们回来看看有问题的原始代码。

// shims-vue.d.ts

declare module '*.vue' {
  import { defineComponent } from 'vue';

  const component: ReturnType<typeof defineComponent>;
  export default component;
}

declare module 'vue-router' {
  interface RouteMeta {
    isPublic?: boolean;
  }
}

这两个declare module语句不能存在于同一文件中,因为其中一个正在尝试声明一个模块'*.vue',另一个正在声明一个模块。因此,我们将declare module '*.vue' {...}留在原处,因为它按预期运行。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?