function hello<Key extends string>(key: Key): { [K in Key]: 123 } {
return ({ [key]: 123 }); // as { [K in Key]: 123 }
}
hello<'myKey'>('myKey');
I don’t get it why the code snippet above produces an error and key is treated as string in [key] instead of Key.
How can I solve it? I commented out a workaround but it just feels wrong.
>Solution :
This is a pretty common issue with the dynamic key. This can be fixed by adding a separate function that will be responsible purely for this operation:
function put<Key extends string, Value>(
key: Key,
value: Value,
): { [K in Key]: Value };
function put<Key extends string, Value>(key: Key, value: Value) {
return { [key]: value };
}
Testing:
function hello<Key extends string>(key: Key): { [K in Key]: 123 } {
return put(key, 123); // no error
}
hello('myKey'); // no error