I wish to define a Map
variable that should hold either a primitive value (string | number | boolean) or another Map
of the same type.
I've tried to do this:
type Primitive = string | number | boolean;
type SafeNestedMap = Map<string, Primitive | SafeNestedMap>;
let states: SafeNestedMap = new Map<string, SafeNestedMap>();
however the compiler complains:
TS2456: Type alias 'SafeNestedMap' circularly references itself.
How can i properly declare this recursive type?
There are some extremely subtle details around how interface
and type
s are different in TypeScript; one caveat of type aliases is that they may not be self-referential (this is because they are immediately expanded, whereas interfaces are expanded later).
You can instead write
interface SafeNestedMap extends Map<string, Primitive | SafeNestedMap> { }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With