Given the following object:
const ROUTES = {
PAGE_NO_PARAMS: '/hello/page/two',
PAGE_R: '/about/:id',
PAGE_Z: '/page/page/:param/:id',
PAGE_N: '/who/:x/:y/:z/page',
} as const
Is it possible a list of types / interfaces for each route so that the developer is restricted to the valid params for the selected route.
Ie. generate a type from ROUTES that has the same outcome as type RouteAndParams below.
interface PageNoParams = {
route: '/hello/page/two' // no params
}
interface Param1 = {
route: '/about/:id',
params: { id: string } // required params
}
interface PAGE_Z = {
route: '/page/page/:param/:id',
params: { id: string; param: string } // required params
}
interface Param3 = {
route: '/who/:x/:y/:z/page',
params: { x: string; y: string; z: string } // required params
}
type RouteAndParams = PageNoParams | Param1 | PAGE_Z | Param3;
// Some examples of expected results / errors when using generated type
// should NOT error
const routeWithParams: RouteAndParams = {
route: '/page/page/:param/:id',
params: { 'param': 'blah', 'id': 'xxx' }
}
// should error as unexpected param 'x'
const routeWithParams: RouteAndParams = {
route: '/about/:id',
params: { 'id': 'xxx', 'x': 'xxx' }
}
// should error as param 'y' is missing
const routeWithParams: RouteAndParams = {
route: '/who/:x/:y/:z/page',
params: { 'x': 'blah', 'z': 'blah' }
}
I hope this all makes sense. I'm trying to replace runtime errors with build errors.