Your type appears to be quite general, given that name and path are simply strings. From this, we can create a structure like so:
type RoutesMap = Record<IRouteProps['name'], IRouteProps['path']>
This can essentially be simplified to:
type RoutesMap = Record<string, string>
To generate such a map without using foreach
, we can utilize the reduce
method (although foreach is still an option, but not as clean as in the original code snippet):
const routes = routesConfig.reduce((routes, route: IRouteProps) => {
routes[route.name] = route.path;
return routes;
}, {} as RoutesMap);
However, with this implementation, the resulting type will only be a map of string: string
. To increase specificity, we could use the const
keyword, for example:
const routesConfig = [
{
path: '/login',
name: 'login'
},
{
path: '/dashboard',
name: 'dashboard'
}
] as const; // note the usage here
type IRouteProps = typeof routesConfig[number];
type RoutesMap = Record<IRouteProps['name'], IRouteProps['path']>
const routes = routesConfig.reduce((routes, route: IRouteProps) => {
routes[route.name] = route.path;
return routes;
}, {} as RoutesMap);
In this scenario, the RoutesMap
type is tailored to reflect values within the routesConfig object.