mobxjs / mobx-state-tree

Full-featured reactive state management without the boilerplate
https://mobx-state-tree.js.org/
MIT License
6.94k stars 640 forks source link

Typescript Error - types.map instance cannot be assigned to Map interface when nested #1991

Closed briedel1 closed 1 year ago

briedel1 commented 1 year ago

Bug report

Sandbox link or minimal reproduction code

const nestedMap: Map<string, Map<string, string>> = types.map(types.map(types.string)).create()

Describe the expected behavior I would expect to be able to assign an instance of types.map to the typescript Map interface. It works so long as the map values are not maps themselves.

Describe the observed behavior The following ts error occurs: TS2322: Type 'IMSTMap<IMapType<ISimpleType<string>>> & IStateTreeNode<IMapType<IMapType<ISimpleType<string>>>>' is not assignable to type 'Map<string, Map<string, string>>'.   Types of property 'set' are incompatible.     Type '(key: string, value: ExtractCSTWithSTN<IMapType<ISimpleType<string>>>) => IMSTMap<IMapType<ISimpleType<string>>> & IStateTreeNode<...>' is not assignable to type '(key: string, value: Map<string, string>) => Map<string, Map<string, string>>'.       Types of parameters 'value' and 'value' are incompatible.         Type 'Map<string, string>' is not assignable to type 'ExtractCSTWithSTN<IMapType<ISimpleType<string>>>'.           Type 'Map<string, string>' is not assignable to type 'IMSTMap<ISimpleType<string>> & IStateTreeNode<IMapType<ISimpleType<string>>>'.             Type 'Map<string, string>' is missing the following properties from type 'IMSTMap<ISimpleType<string>>': put, merge, replace, toJSON, and 2 more.

briedel1 commented 1 year ago

FWIW - To deal with this, I've moved all my map write operations inside the state tree actions and changed the interfaces taking the tree as input from Map to ReadonlyMap. This is probably a best practice anyway.

coolsoftwaretyler commented 1 year ago

Thanks for the followup @briedel1!

Do you still have a CodeSandbox handy for this? Or can you provide some code snippet to show other people how you solved it?

One way or another, how do you feel about closing this issue out, since it seems like you came to a good resolution?

coolsoftwaretyler commented 1 year ago

Since it's been a few months with no response, and OP got a resolution, I'm going to close this out.