如何将键数组映射到对象属性类型

时间:2020-03-22 10:51:38

标签: typescript typescript-typings

我想传递一个键数组并从中推断返回类型,这是我到目前为止尝试过的

type Obj = {
  cats: string
  dogs: string
}

type MapKeys<K extends [keyof Obj]> = {
  [P in K[number]]: Obj[P]
}

declare const obj: Obj

const cats: MapKeys<['cats']> = {
  cats: 'hi', // ok
} 

const catsAndDogs: MapKeys<['cats', 'dogs']> = { // error about the length but the types are ok
  cats: 'hi',
  dogs: 'hello'
} 

const getProps = (keys: [keyof Obj]): MapKeys<typeof keys> => keys.reduce((acc, key) => ({
  ...acc,
  [key]: obj[key]
}), {} as MapKeys<typeof keys>)

const getCats = getProps(['cats']) // the types are the whole Obj
const getCatsAndDogs = getProps(['cats', 'dogs']) // same error about the length

playground

1 个答案:

答案 0 :(得分:0)

如Jeffrey所建议,我将MapKeys中的类型切换为

type MapKeys<K extends (keyof Obj)[]>

,然后在getProps

const getProps = <K extends (keyof Obj)[]>(keys: K): MapKeys<K> =>
  keys.reduce(
    (acc, key) => ({
      ...acc,
      [key]: obj[key],
    }),
    {} as MapKeys<K>,
  )