Tomáš M.
Tomáš M.

Reputation: 744

How to specify type of an arrow function defined as an object literal in TypeScript?

I have the following object:

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

This specifies a route object for Vue Router. The problem is with function beforeEnter, as I get a TS7006 error - all parameters implicitly have any type.

I could specify the parameter types by hand, but there already exists the exact type the beforeEnter function is supposed to fit - it's called NavigationGuard, and I can import it from vue-router just fine.

The problem comes when I try to specify it, I can't seem to find the right syntax. I found the question "Type definition in object literal in TypeScript" where an answer suggests either specifying the type of the entire object, or casting it like so: { hasStarted: <boolean> null, ... } but replacing the definition with

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

doesn't seem to appease the compiler.

What to do?

Upvotes: 4

Views: 363

Answers (1)

Paleo
Paleo

Reputation: 23712

In order to avoid the confusion with generics, you need parenthesis:

<NavigationGuard>((to, from, next) => {
  // …
})

Or:

((to, from, next) => {
  // …
}) as NavigationGuard

But you should be able to use typing on the parent object:

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

Upvotes: 1

Related Questions