2

I have a type A where keys are strings and values are some datatype. (see below)

Now I want to create a Map<K,V> where K is a key of A and V is of the corresponding datatype in A. (see my attempt below)

type A = {
  a: boolean,
  b: number,
};

const myMap: Map<keyof A, A[keyof A]> = new Map();
myMap.set('a', 1); // bad

// only this should be allowed:
myMap.set('a', true);
myMap.set('b', 1);

My approach doesn't work since the first keyof A must not necessarily be the same as the second keyof A. What is the correct way to achieve this?

Page not found
  • 2,454
  • 2
  • 10
  • 19
  • `typeof keyof A…` – Mytch Jun 09 '22 at 02:13
  • 1
    `Map` isn't strongly typed enough for you to represent this (much like `Record` can't represent arbitrary object types). See the answer to the linked question for more information; if I use the `ObjectMap` typings from there I get [this code](https://tsplay.dev/mLqL4W). At runtime that's still a `Map` (in the JavaScript sense) but the TypeScript typings are typed to expect object key-value pairs. Not sure I've ever really understood the use case for this over just a plain object, though. – jcalz Jun 09 '22 at 02:29
  • The Map problem was just an example and occurs in other scenarios as well. – Page not found Jun 09 '22 at 10:42

0 Answers0