javascript - 下面代码的类型约束怎么写
问题描述
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'的类型约束?
解决方案
您的类型不是很具体,因为名称和路径是字符串。因此,您可以从中建模的结构是:
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 对象中的值。
推荐阅读
- javascript - 如何使用 API ajax 调用实现动态表并将数据填充到数据表中?
- json - 如何展开 JSON 对象?
- c# - Switch 语句包含具有相同标签值的多个案例,但不包含
- java - Java关于反序列化继承类的一些问题
- c# - 从 Serilog 将事件摄取到 Seq 中的问题
- javascript - 代码:'MODULE_NOT_FOUND',requireStack[] node.js
- r - R:按行替换值
- reactjs - 我打电话给网络一次,但在测试中它被抓了两次
- php - 从后到前发送错误消息(php + html)
- php - 如何用pdo根据store一一拉取