Angular 将角度布线映射到其关键点为路径属性的类型
我有这样的路线Angular 将角度布线映射到其关键点为路径属性的类型,angular,typescript,mapping,typescript-generics,Angular,Typescript,Mapping,Typescript Generics,我有这样的路线 const routes = [ { path: 'path1' }, { path: 'path2', children: [{ path: 'path3' }] }, ] as const; 我想要一张这样的地图 type map = { path1: {}; path2: { path3: {} } }; 那么,我如何更正下面的类型,以便从上面提供的路线获取地图 type MappedRoutes<TRoutes> = { [K in keyof
const routes = [
{ path: 'path1' },
{ path: 'path2', children: [{ path: 'path3' }] },
] as const;
我想要一张这样的地图
type map = { path1: {}; path2: { path3: {} } };
那么,我如何更正下面的类型,以便从上面提供的路线获取地图
type MappedRoutes<TRoutes> = {
[K in keyof TRoutes]: TRoutes[K] extends {children: unknown, path: string, }
? {TRoutes[K]['path']: MappedRoutes<TRoutes[K]['children']>}
: TRoutes[K]['path'];
}
我可能会这样写:
type Routes = readonly { path: string, children?: Routes }[];
type MappedRoutes<T extends Routes> = {
[K in T[number]["path"]]: (Extract<T[number], { path: K }>['children'] extends infer R ?
R extends Routes ? MappedRoutes<R> extends infer O ? {
[P in keyof O]: O[P]
} : never : {} : never)
}
如果T
可分配给Routes
,一个{path:string,children?:Routes}
数组,则MappedRoutes
的键位于T[number][“path”]
。。。其中,T[number]
是数组元素类型的并集,T[number][“path”]
是它们的path
属性的并集
然后,对于这些键中的每一个K
,我们得到Extract['children']
,这是对应于该路径的children
属性。(Extract
)获取数组元素的并集,并仅提取可分配给{path:K}
的元素。然后我们得到它的children
属性)
我们检查此子属性。它本身是一个路由吗?如果是,则递归地生成它的mappedrouts
。这里有相当多的条件类型推断,但这主要是为了将类型存储到类型变量中,而不是重写它们R
是children
属性,O
是映射的children
属性(如果存在)。我遍历了O
,因此映射的
类型被急切地递归扩展到它的最终形式,而不是像{path1:{},path2:mappedrouts}
那样离开它
好吧,希望这会有帮助;祝你好运
type Routes = readonly { path: string, children?: Routes }[];
type MappedRoutes<T extends Routes> = {
[K in T[number]["path"]]: (Extract<T[number], { path: K }>['children'] extends infer R ?
R extends Routes ? MappedRoutes<R> extends infer O ? {
[P in keyof O]: O[P]
} : never : {} : never)
}
type Mapped = MappedRoutes<typeof routes>
/* type Mapped = {
path1: {};
path2: {
path3: {};
};
} */