Let’s say I have a Map with keys A and B that each store a boolean value, and keys X and Y that each store their own array of string. The simplest way to type this would be to write:
type CustomType = Map<string, boolean | string[]>
However, if I write the following code wherein I’ll know the value type, TypeScript will be uncertain of the values type:
for (const [key, value] of MyMap) {
switch(key) {
case 'A' || 'B':
// value will only be boolean but typescript thinks the value
// could still be a string[],
break
case 'X' || 'C':
// and vice versa.
break
}
}
Using a union as the following tells TypeScript that the Map as a whole will only be one or the other:
type CustomType = Map<'A' | 'B', boolean>
| Map<'X' | 'Y', string[]>
Switching to intersection type seems to ignore the second half.
type CustomType = Map<'A' | 'B', boolean>
& Map<'X' | 'Y', string[]>
Does TypeScript have a way to properly type this that doesn’t require adding unnecessary type checks or littering my code with @ts-ignore
comments?