首页 > 解决方案 > 下面代码的类型约束怎么写

问题描述

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;
});

我想从对象数组中获取每个对象的值,然后将此值用作另一个对象的键。

如果你使用 typescript 来约束这个新对象的类型,你会怎么写呢?

如何编写'routeNames'的类型约束?

标签: javascripttypescript

解决方案


您的类型不是很具体,因为名称和路径是字符串。因此,您可以从中建模的结构是:

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 对象中的值。


推荐阅读