Similar to:
How to infer a typed array from a dynamic key array in typescript?
I'm looking to type a generic object which receives a map of arbitrary keys to lookup values, and returns the same keys with typed values (like a typed _.mapValues).
The ability to get a singular typed property from an object is documented and works. With arrays, you need to hardcode overloads to typed tuples, but for objects i'm getting a 'Duplicate string index signature' error.
export interface IPerson {
age: number;
name: string;
}
const person: IPerson = {
age: 1,
name: ""
}
function getProperty<T, K extends keyof T>(o: T, name: K): T[K] {
return o[name];
}
const a = getProperty(person, 'age');
// a: number
const n = getProperty(person, 'name');
// n: string
function getProperties<T, K extends keyof T>(obj: T, keys: { [key: string]: K }) {
const def: { [key: string]: T[K] } = {};
return Object.entries(keys).reduce((result, [key, value]: [string, K]) => {
result[key] = getProperty(obj, value);
return result;
}, def);
}
const { a2, n2 } = getProperties(person, {
a2: 'name',
n2: 'age'
});
// Result:
// {
// a2: string | number,
// n2: string | number
// }
// What I'm looking for:
// {
// a2: string,
// n2: number'
// }
How can this be implemented with typescript?