How to declare a recursive map type in Typescript (TS2456: Enter the alias '*', which refers to itself circularly).

I want to define a variable Mapthat should contain either a primitive value (string | number | boolean), or another of Mapthe same type.

I 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 correctly declare this recursive type?

+4
source share
1 answer

In TypeScript there are some extremely subtle details of how interfaceand typedifferent; one of the caveats of type aliases is that they cannot be self-referential (this is because they expand immediately and interfaces expand later).

interface SafeNestedMap extends Map<string, Primitive | SafeNestedMap> { }
+6

Source: https://habr.com/ru/post/1694209/


All Articles