I'm trying to construction a function where you pass an object, and an array of keys (This is a simplified example to illustrate what im trying to achieve). Then return is an array that contain those keys, and has the type of a tuple. The problem that I'm struggling with is that the return type is the union of all types in the type, not the actual value of the given key.
I guess the error lies in the K parameter not infering the key granular enough..? Is this even solveable?
type User = {
name: string,
location: string
age: number
}
const fooUser: User = {
age: 30,
name: "Foo",
location: "Bar",
}
const getSelected = <T extends User, K extends (keyof User)[]>(user: T, keys: K) => {
return keys.map((k) => user[k])
}
// this errors but gives correct types
type InferKeys <T extends (keyof User)[] > = T extends [infer First, ...infer Rest] ? First extends keyof User ? [User[First], ...InferKeys<Rest>] : [User[First]] : []
type MyInferedKeys = InferKeys<['age', 'name']>
// ^? type MyInferedKeys = [number, string]
const testArray = getSelected(fooUser, ['age', 'name'])
// ^? const testArray : (string | number)[]
// Would want [string, number]