Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I declare a recursive Map type in Typescript (TS2456: Type alias '*' circularly references itself.)

Tags:

typescript

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?

like image 680
coderatchet Avatar asked Feb 28 '18 02:02

coderatchet


1 Answers

There are some extremely subtle details around how interface and types 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> { }
like image 69
Ryan Cavanaugh Avatar answered Oct 20 '22 18:10

Ryan Cavanaugh