1

I would like to declare a map member variable in class. What I currently have is the following:

(This compiles)

this.map = new Map <keyof T, T[keyof T]> ()

But I would like to constraint the values in the map to specific type based on the key type. Ultimately what I need is the value type to be T[K]

Class parameterized type should include only the T.

Is this actually even possible?

DimitriosP
  • 106
  • 1
  • 8
  • Given `Map` is typed as `Map` - it's impossible. – zerkms Feb 24 '21 at 21:35
  • Just like in the other question, I wonder why this we want this instead of just a value of type `T` or `Partial`, but ‍♂️ – jcalz Feb 24 '21 at 21:37
  • Im not sure how Partial would solve the problem. – DimitriosP Feb 24 '21 at 21:46
  • Can you explain why you would want to store a value `map` of this special `Map` type as opposed to a value `x` of type `T` or `Partial`? What, specifically, are you doing with a `Map` that wouldn't be easier or more natural with the object? `map.get("a")` looks like `x.a`; `map.set("a", 123)` looks like `x.a = 123`; `map.has("a")` looks like `"a" in x`; You can iterate over object props with `Object.entries()` or `Object.keys()` or `Object.values()`. I'm not saying you don't have a good use case; i just have a hard time envisioning one. – jcalz Feb 24 '21 at 21:54
  • In any case, the [answer to the other question](https://stackoverflow.com/a/54908008/2887218) has an `ObjectMap` type that should work the way you want. – jcalz Feb 24 '21 at 21:59
  • @jcalz Used case would be getting correct value type based on the key. for example, map.get("numberKey") would give value of type number – DimitriosP Feb 24 '21 at 22:31
  • And how is that better than just reading the `numberKey` property on a value of type `T`? That’s what objects are for: reading and writing properties whose keys are strings. What advantage does a map give you over a plain object type? Right now I can’t tell if you’ve considered using a plain object but dismissed it for a reason you haven’t said, or if you just haven’t considered it or understood the suggestion. – jcalz Feb 24 '21 at 22:46

0 Answers0