Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Type '{ [x: string]: number; }' is not assignable to type '{ [K in Key]: 123; }'

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading