2

I have been trying without success on trying to infer the typing of the second generics parameter based on the first one. Currently I have the following implementation.

interface IProps {
  [propertyName: string ]: boolean | number | string
}

class myClass <T extends IProps> {
...
private _map = new Map < keyof T, Array< T[keyof T]>>();
...
}

The problem is that I am unable to limit the typings of the array depending on the linked type of the entry of the map.

If I have a

{ 
  x:"string",
  y:0
}

I would like to restrict my map so that I would only be able to refer to Array<string> when calling _map.get("x") and only Array<number> when calling _map.get("y").

Thomas
  • 174,939
  • 50
  • 355
  • 478
  • The property in the class is called `_map` but you want to access `map`. Is that a typo? – Tobias S. Aug 30 '22 at 10:55
  • I don't think you can do this using a `Map`, because its values always all have the same static type. You might be able to do it using a mapped type, but you would also need to make `IProps` less general (without the index signature) to make that work. – Thomas Aug 30 '22 at 11:05
  • 1
    The typings for `Map` don't work that way; you'd have to write your own as shown in the answer to the linked question (although I still never quite understand why people reach for `Map` when plain objects already behave this way). – jcalz Aug 30 '22 at 15:32

1 Answers1

0

There is no correlation between keyof T and Array<T[keyof T]>.

Any key from T will return any value type from T.

Radu Diță
  • 13,476
  • 2
  • 30
  • 34