我想传递一个键数组并从中推断返回类型,这是我到目前为止尝试过的
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
答案 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>,
)