打字稿 - 将数组转换为键控对象(中等复杂)

时间:2021-01-15 23:46:21

标签: typescript

见下文,我似乎无法将对象中的每个键都限制为其数组条目。

相反,结果将接受所有 func 属性的联合(例如 ()=>'test1' | ()=>'test2' | ()=>'test3'

有人知道如何解决这个问题吗?


type convertArrayToObject<T extends { key: string, func: ()=>string }[]> = {
  [I in keyof T as Extract<T[I], T[number]>["key"]] : 
      Extract< 
          Extract<T[I], T[number]>, // All entries in array
          {
              key: Extract<T[I], T[number]>['key'] // Extract out all entries whose key does not match the current iteration's
          }
      >['func']; // Grab function
};

type fragments_T = [
    {
        key: 'test1',
        func: ()=>'test1'
    }, 
    {
        key: 'test2', 
        func: ()=>'test2'
    }, 
    {
        key: 'test3', 
        func: ()=>'test3'
    }
]

 const recipe_WIP: convertArrayToObject<fragments_T> = {
     test1: ()=>"test1",
     test2: ()=>"test1", // !!!!!!! Should be limited to ()=>'test2' !!!!!!!!!!
     test3: ()=>"test1", // !!!!!!! Should be limited to ()=>'test3' !!!!!!!!!!
 }

TS Playground

0 个答案:

没有答案
相关问题