Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 将角度布线映射到其关键点为路径属性的类型_Angular_Typescript_Mapping_Typescript Generics - Fatal编程技术网

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: {};
    };
} */