I need to implement a function called valueToObject
that takes a key and a value as arguments and returns an object with that key and value pair, like this:
valueToObject('myKey', 3);
// should yield {myKey: 3}
I attempted to write the following code:
type Wrapped<K extends string, V> = {
[P in K]: V;
};
function valueToObject<K extends string, V>(key: K, value: V): Wrapped<K, V> {
return {[key]: value};
}
However, this code does not compile without casting the return value to any
:
error TS2322: Type '{ [x: string]: V; }' is not assignable to type 'Wrapped<K, V>'.
How can I modify this function to ensure type safety?