I'm trying to wrap my head around types in Typescript. In general it's going well but I'm struggling to convert this function from Javascript to Typescript.
export function keyed(object, key, value) {
const newKey = object[key];
const newValue = object[value];
const newObject = {};
newObject[newKey] = newValue;
return newObject;
};
This is my attempt so far:
type ValueOf<T> = T[keyof T];
export function keyed<T, K extends keyof T>(object: T, key: K, value: K): { [key: ValueOf<T>]: ValueOf<T> } {
const newKey: ValueOf<T> = object[key];
const newValue: ValueOf<T> = object[value];
const newObject: { [key: ValueOf<T>]: ValueOf<T> } = {};
newObject[newKey] = newValue;
return newObject;
};
But, I'm getting a few errors like:
An index signature parameter type cannot be a literal type or generic type. Consider using a mapped object type instead.ts(1337)
and
Type 'ValueOf<T>' cannot be used to index type '{}'.ts(2536)
I've tried to use underscores DefinitelyTyped definitions to help out over here, since they do quite a bit of these operations but I haven't had any luck. Is it impossible?