1

I am using a Qraphql code generator that generates the schema types in typescript and would like to use those types inside the model.

My question is how can I use a typescript type inside the Mobx state tree model like this

type AssignedFilter = {
  id: number
  name: string
  email: string
}

const SearchStore = types
  .model('Search', {
    text: '',
    assigned: // how to use the AssignedFilter type here??
  })
Yassir Hartani
  • 157
  • 1
  • 6

1 Answers1

1

A type is a pure TypeScript concept, so it's not possible to use a type to define what MST type a property should be.

You can however do it the other way around and create a type from your MST models, if that suits your use case.

Example

const AssignedModel = types.model('Assigned', {
  id: types.identifierNumber,
  name: types.string,
  email: types.string
});

const SearchStore = types.model("Search", {
  text: "",
  assigned: AssignedModel
});

type AssignedFilter = SnapshotIn<typeof AssignedModel>;
Tholle
  • 108,070
  • 19
  • 198
  • 189
  • 1
    Thanks, but I don't want to go this route as some types may get too big and it will be waste of time to not reuse the existing Typescript `types`. However, I found another way to do that but I don't quite get it even if it's working assigned: types.maybeNull(types.frozen()), – Yassir Hartani Sep 08 '22 at 17:39
  • 1
    @YassirHartani I see. Yes, that's a nice way to go about it, granted that `assigned` is a kind of immutable and serializable value, but it will not be e.g. a typed `AssignedModel` with views, actions, etc. – Tholle Sep 08 '22 at 17:43
  • 1
    my usecase is very simple, I will interact with the assigned from the SearchStore action, for example `changeAssignee(newAssignee) {self.assigned = newAssignee}` But if I understand correctly the only downside is not having direct manipulation of the assignee as a model so I will need to always interact with it from the SearchStore. on the other side, I'm getting a hard time understanding the types.frozen can you provide an example on when to use this type(I only used it to reuse the ts types) – Yassir Hartani Sep 08 '22 at 17:59
  • 1
    @YassirHartani `frozen` can be useful if you are not interested in modelling and interacting with a particular part of your state tree, but still want it in the tree. [It can e.g. be useful when storing a JSON dump from a service](https://codesandbox.io/s/withered-wildflower-rke84h?file=/src/App.js). – Tholle Sep 09 '22 at 11:39