Search code examples
typescriptreact-nativemobx-state-tree

How to define a model with mobx-state-tree with unknown properties


I have to create a model using MobX-State-Tree that represents the response of an API. The response is like this TypeScript type:

type Tree = {
  question: string,
  field: string,
  options: Record<string, Tree>
};

If you look close, you will see it uses a TS Record and recursive approach and I couldn't find how to reproduce the options type it in MST. So far I'm stuck with:

import { types } from "mobx-state-tree"

export const Tree = types
  .model("Tree")
  .props({
    question: types.string,
    field: types.string,
    options: ???

Solution

  • const Tree = types.model({
      id: types.identifier,
      question: types.string,
      field: types.string,
      options: types.map(types.late(() => Tree))
    })
    

    Handle circular dependencies between files and types using late

    And late api overview