typed-route
Type safe routes developed for React Router
Quick example:
// constants/routes.ts; ; // routes.tsx; ; // pages/sub-form.tsx;;; ; ; // navigation.tsx;; ;
Quick Start
Requirements
- npm or Yarn
- Node.js 10.0.0 or higher
- Typescript 3.5.0 or higher
Installation
$ npm install typed-route
If you are using Yarn, use the following command.
$ yarn add typed-route
Usage
typedRoute
typedRoute
- generic function creates string with saved context
typedRoute<'name'>('/:name')
- creates a string route with one param { name: string }
typedRoute<'id' | 'name'>('/:id/:name')
- creates a string route with a few params { id: string, name: string }
typedRoute<'id', 'name'>('/:id/:name?')
- you can add optional params { id: string, name?: string }
routeMap
Creates a route map merging all routes string and contexts
;routes = routeMap'/base', ;console.logroutes;/* { index: '/base', page1: '/base/page1', page2: { index: '/base/page2', info: '/base/page2/info', form: '/base/page2/form' }} */
reverseUrl
Type safe function generates an url using typed route and route params
reverseUrl typedRoute'/item',; // item reverseUrl typedRoute'/item/:id', ; // item/1 reverseUrl typedRoute'/item/:id',; // TS Error reverseUrl typedRoute'/item/:id', ; // TS Error: Property 'id' is missing reverseUrl typedRoute'/item/:id/:second', ; // item/1/2 reverseUrl typedRoute'/item/:id/:optional?', ; // item/1 reverseUrl typedRoute'/item/:id/:optional?', ; // item/1/test
InferTypedRoute
Infer params from types route
;;// { id: string } route = typedRoute'/item/:id/:second';;// { id: string; second: string } route = typedRoute'/item/:id/:optional?';;// { id: string; optional?: string } ;;// { id: string; sub: string }
You can use it with react-router
; ;
InferRouteMap
Generates route map type params
;;/* { list: object; form: { index: { id: string }; info: { id: string }; subForm: { index: { id: string }; detail: { id: string; sub: string } } }*/
And you can use it with react-router instead of InferTypedRoute
; ;