kitbagjs / router

A type safe router for vuejs
MIT License
131 stars 1 forks source link

Make `route` a union of all possible routes and improve return types for `isRoute` and `useRoute` #209

Closed pleek91 closed 1 week ago

pleek91 commented 1 week ago

Description

This PR updates the type for the current route to be a discriminating union of possible routes. This means that when accessing the route via router.route or by using the useRoute composition the route can easily be narrowed.

Given the following routes

const routes = createRoutes([
  {
    name: 'parentA',
    path: '/parentA',
    children: createRoutes([
      {
        component,
        name: 'childA',
        path: '/childA/[paramA]',
      },
    ]),
  },
  {
    name: 'parentB',
    path: '/parentB',
    component,
  },
])

const router = createRouter(routes)

router.route.key is type 'parentA' | 'parentB' | 'parentA.childA'. And router.route.params is type {} | { paramA: string }. Which means you can narrow the route in a type safe way by doing things like this

const route = router.route

if(route.key === 'parentA.childA') {
  console.log(route.params.paramA) // correctly knows that `paramA` is a valid param
}

isRoute and useRoute

This gets even more useful when combined with the isRoute type guard that is exported by router. By default isRoute is not an exact route match, meaning it will match any route AND any children of that route.

if(isRoute(route, 'parentA')) {
  // route.key is type 'parentA' | 'parentA.childA'
}

If you want to match only an exact route you can pass the exact option into isRoute

if(isRoute(route, 'parentA', { exact: true })) {
  // route.key is type 'parentA'
}

This works exactly the same when using useRoute

const route = useRoute('parentA')
// route.key is 'parentA' | 'parentA.childA'
const route = useRoute('parentA', { exact: true })
// route.key is 'parentA'

This makes working with routes in a type safe way much easier and more flexible.

netlify[bot] commented 1 week ago

Deploy Preview for kitbag-router ready!

Name Link
Latest commit 547f4c28369e04157f4410bc228a252eef3076e5
Latest deploy log https://app.netlify.com/sites/kitbag-router/deploys/667b8db80ba9a50008371642
Deploy Preview https://deploy-preview-209--kitbag-router.netlify.app
Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.