interface IRouteProps {
path: string
name: string
}
const routesConfig: IRouteProps[] = [
{
path: '/login',
name: 'login'
}
];
let routeNames: any;
const routes: IRouteProps[] = routesConfig.forEach((route: IRouteProps) => {
routeNames[route.name] = route.path;
});
我想从对象数组中获取每个对象的值,然后将该值用作另一个对象的键。
如果使用打字稿来约束此新对象的类型,该如何编写?
如何编写“ routeNames”的类型约束?
您的类型不是很明确,因为名称和路径是字符串。因此,您可以从中建模的结构是:
type RoutesMap = Record<IRouteProps['name'], IRouteProps['path']>
真正等于什么:
type RoutesMap = Record<string, string>
现在要创建这样的,而不是foreach
,我们应该使用reduce
(是的,我们也可以使用foreach,但不能像原始代码示例中那样用作表达式):
const routes = routesConfig.reduce((routes, route: IRouteProps) => {
routes[route.name] = route.path;
return routes;
}, {} as RoutesMap);
但是我们得到的类型仅仅是map string: string
。我们可以通过例如const
关键字来更具体。考虑:
const routesConfig = [
{
path: '/login',
name: 'login'
},
{
path: '/dashboard',
name: 'dashboard'
}
] as const; // pay attention 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);
在这种情况下,RoutesMap
将指定给routesConfig对象中现有的值。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句