How can I define a map where each key has a certain type assigned ?
This is the type def:
type Data = {
articles: Article[],
comments: Comment[],
...
}
And the map def has to accept only keys from that type, but the values have to match the keys:
type MyMap = <K extends keyof Data>Map<K, Data[K]>; // <- doesn't work
2
Answers
You can make a generic type, that uses a distributed conditional type
This builds a union of
Map
types for each key (K
) fromData
and with the associated value type (O[K]
):To break it down a little, the
MyMap<Data>
is the same asMyMap<Data, keyof Data>
(due to the default on the second generic type).keyof Data
can also be written as a union type of"articles" | "comments"
:The conditional type of
K extends any
is then applied to each member of the"articles" | "comments"
union. SoMyMap
distributes on each element, effectively giving:When ultimately gives:
I think what you’re looking for is something like the following:
This is a copy of the
Map
type, but I have changed the generics to accept only an object-like value (which will retain the exact key-value mappings).I have also overridden most of the methods so that the types are stricter. The only one I have left out is
forEach
which uses the existingMap.forEach
as our new type extends theMap<K, V>
type.