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

How can I get the key and value types out of a Map<unknown,unknown>?

e.g. I’m trying to write a function like this:

export function fpMapSet<M extends Map<unknown,unknown>>(key: KEY_TYPE, value: VALUE_TYPE) {

Where KEY_TYPE ought to be whatever that first unknown actually is, and VALUE_TYPE should be the 2nd unknown.

And yes, I know I can write it like this:

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

export function fpMapSet<K,V>(key: K, value: V) {

But that’s not the question.

>Solution :

Given the question as asked, you could use conditional type inference via infer to extract the key and value types:

type MapKeyType<M> = M extends Map<infer K, any> ? K : never;
type MapValueType<M> = M extends Map<any, infer V> ? V : never;
declare function fpMapSet<M extends Map<unknown, unknown>>(
  key: MapKeyType<M>, value: MapValueType<M>): void;

And you can verify that it works:

const fpMapSetStringNumber = fpMapSet<Map<string, number>>;
// const fpMapSetStringNumber: (key: string, value: number) => void

The above is an instantiation expression showing how you can set M to Map<string, number> and leave the function uncalled. You can of course call instantiate M and call the function at the same time:

fpMapSet<Map<string, number>>("abc", 123);

Playground link to code

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