如何解决如何在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规范,模块定义为包含一个或多个顶级import
或export
语句的文件。
不是模块的文件中的代码片段完全符合您 的注意。它代替'vue-router'
包的任何其他类型,而不是增加它们。但是我们想增加该程序包的类型,而不是替换它们。
但是,打算用作声明而非扩展的declare module
语句必须位于文件中,而该文件不是模块。也就是说,在文件 不 中包含任何顶级import
或export
语句。
要解决此问题,请将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 举报,一经查实,本站将立刻删除。