Как сопоставить массив ключей с типами свойств объекта - PullRequest
0 голосов
/ 22 марта 2020

Я хочу передать массив ключей и определить тип возвращаемого значения, это то, что я пробовал до сих пор

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

детская площадка

1 Ответ

0 голосов
/ 22 марта 2020

Как предложил Джеффри, я переключил тип в 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>,
  )
...