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 interface, not the actual value of the given key.
I tried adding the const parameter to the function but to no avail. I guess the error lies in the K parameter not infering the key granular enough..?
type User = {
name: string,
location: string
age: number
}
const fooUser: User = {
age: 30,
name: "Foo",
location: "Bar",
}
const getSelected = <T extends User, const K extends readonly(keyof User)[]>(user: T, keys: K) => {
return keys.map((key) => user[key]);
}
const [age, userName] = getSelected(fooUser, ['age', 'name'])
// ^? const age: string | number
// Would want the array typed as [string, number]