Typescript: How to infer the second parameter Type based on the first one in a typescript generics

Viewed 28

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").

1 Answers

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

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

Related