我正在尝试从 vue 路由器的路由生成路由名称。 目标是使用辅助函数
findRouteByName()
来查找路线。
但是辅助函数的参数应该具有真正的
route.name
作为类型。
当我尝试这样做时,出现以下错误:
The type 'readonly [{ readonly path: "/"; readonly name: "Root"; readonly children: readonly []; },
{ readonly path: "/somePath"; readonly name: "somePath1"; readonly component: "Blub"; readonly
children: readonly []; }, { readonly path: "/somePath2"; readonly name: "somePath2"; readonly
component: "Blub"; readonly children: ...' is 'readonly' and cannot be assigned to the mutable type
'RouteRecordRaw[]'.(4104)
但是有一个办法...
图片中的示例仅在我不给路线指定类型
RouteRecordRaw[]
时才有效。
然后我就可以实现我的目标并使用函数中的类型作为参数了。
但是我必须而且应该给出
RouteRecordRaw[]
作为路线类型。否则路由器初始化的时候会报错。
所以它应该与RouteRecordRaw[]
一起使用。
我已经在 Stackblitz 上准备好了一切,也许你们中的一个人会为此找到一个优雅的解决方案。
尝试用
satisfies RouteRecordRaw[]
代替 as const
。
你会得到同样的类型扣除,但ts不会因为额外的费用而对你大喊大叫
readonly
s
这是一种确保所有类型都得到满足的方法,并且您还可以获得
findRouteByName
- 的智能感知
router/index.ts
import {
RouteRecordRaw,
_RouteRecordBase,
createRouter,
createWebHistory,
} from "vue-router";
type ForceMergeTypes<T, K> = T | (K & Record<never, never>);
type Paths = "/" | "somePath" | "somePath2";
type Names = "Root" | "somePath" | "somePath2";
type ExtendedRouteRecordBase = _RouteRecordBase & {
path: ForceMergeTypes<Paths, RouteRecordRaw["path"]>;
name?: ForceMergeTypes<Names, RouteRecordRaw["name"]>;
};
type RoutesRecord = ExtendedRouteRecordBase & RouteRecordRaw;
const routes: Array<RoutesRecord> = [
{
path: "/",
name: "Root",
component: null,
children: [],
},
{
path: "/somePath",
name: "somePath1",
component: null,
children: [],
},
{
path: "/somePath2",
name: "somePath2",
component: null,
children: [],
},
];
export function findRouteByName(name: (typeof routes)[number]["name"]) {
return routes.find((route) => route.name === name);
}
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes,
});
findRouteByName("");
export default router;
通过这种方法,您可以为
path
和 name
提供任何字符串,并为添加到类型 Path
和 Names
的字符串获得智能感知。如果我遗漏了什么或者不符合您的要求,请告诉我。