ts问题, 根据数组Pick对象

image.png
怎样改getMapObj2, 才可以让obj2推断出来的类型, 长得像ty111一样

function getMapObj2<T extends Record<string, any>, K extends readonly string[]>(originObj: T, keyArr2: K): {
  [Key in typeof keyArr2[number]]: T[Key]
} {
  // let originObj = JSON.parse(JSON.stringify(originObj))
  let obj3 = {}
  let keyArr3 = keyArr2.filter(Boolean)
  Object.keys(originObj).filter(v => keyArr3.includes(v)).forEach(v => {
    obj3[v] = originObj[v]
  })
  return obj3 as { [Key in K[number]]: T[Key]; }
}
let obj4 = {
  a: [1, 2, 3],
  b: 'xx',
  c: 3,
  d: false
}
type arr6 = ['a'] | ['b']
let arr2: arr6 = ['a']
if (Math.random() > 0.5) {
  arr2 = ['b']
}



let obj2 = getMapObj2(obj4, arr2)

// 怎样改getMapObj2, 才可以让obj2推断出来的类型, 长得像ty111一样

type ty111 = {
  a: number[];
} | {
  b: string;
}
阅读 1.1k
1 个回答
function getMapObj2<T extends Record<string, any>, K extends (keyof T)[]>(originObj: T, keyArr2: K): {
    [key in K[number]]: {[k in key]: T[k]}
}[K[number]]
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题