【问题标题】:How to specify type of an arrow function defined as an object literal in TypeScript?如何在 TypeScript 中指定定义为对象文字的箭头函数的类型?
【发布时间】:2019-10-06 20:26:08
【问题描述】:

我有以下对象:

  let route = {
    path: "/login",
    name: "login",
    component: Login,
    beforeEnter: (to, from, next) => {
      if (store.state.system.loggedIn) {
        next("/");
      } else {
        next();
      }
    },
  }

这为 Vue Router 指定了一个路由对象。问题出在函数 beforeEnter 上,因为我收到 TS7006 错误 - 所有参数都隐含地具有 any 类型。

我可以手动指定参数类型,但已经存在 beforeEnter 函数应该适合的确切类型 - 它称为 NavigationGuard,我可以从 vue-router 导入它就好了。

当我尝试指定它时,问题就来了,我似乎找不到正确的语法。我发现了问题“Type definition in object literal in 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();
      }
    },
  }

似乎无法安抚编译器。

怎么办?

【问题讨论】:

    标签: typescript vue-router


    【解决方案1】:

    为了避免与generics混淆,需要括号:

    <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();
        }
      },
    }
    

    【讨论】:

      猜你喜欢
      • 2017-03-09
      • 2021-12-31
      • 1970-01-01
      • 2017-06-12
      • 2023-01-08
      • 1970-01-01
      • 2022-01-22
      • 2016-08-11
      相关资源
      最近更新 更多