我有以下对象:
let route = {
path: "/login",
name: "login",
component: Login,
beforeEnter: (to, from, next) => {
if (store.state.system.loggedIn) {
next("/");
} else {
next();
}
},
}
这为Vue路由器指定路由对象。问题出在函数beforeEnter
,因为出现TS7006错误-所有参数隐式具有any
类型。
我可以手动指定参数类型,但是已经存在该beforeEnter
函数应该适合的确切类型-称为NavigationGuard
,可以vue-router
很好地导入它。
当我尝试指定它时,问题就来了,我似乎找不到正确的语法。我发现了一个问题“ TypeScript中的对象文字中的类型定义”,该问题的答案建议指定整个对象的类型,或像这样强制转换:{ hasStarted: <boolean> null, ... }
但将定义替换为
let route = {
path: "/login",
name: "login",
component: Login,
beforeEnter: <NavigationGuard> (to, from, next) => {
if (store.state.system.loggedIn) {
next("/");
} else {
next();
}
},
}
似乎并不安抚编译器。
该怎么办?
为了避免与泛型混淆,您需要使用括号:
<NavigationGuard>((to, from, next) => {
// …
})
要么:
((to, from, next) => {
// …
}) as NavigationGuard
但是您应该能够在父对象上使用键入:
let route: RouteConfig = {
path: "/login",
name: "login",
component: Login,
beforeEnter: (to, from, next) => {
if (store.state.system.loggedIn) {
next("/");
} else {
next();
}
},
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句