How to describe model of mobx-state-tree with interface of typescript?
Asked Answered
B

1

5

I have some interfaces already, and I want to describe models with this interfaces, just like the code below. Otherwise I have to write again by using types of mobx-state-tree. But this is not the right way, what is the valid solution ?

    import { types } from 'mobx-state-tree';

    export interface IPeople {
      name: string;
      age: number;
    }

    const Peoples = types
      .model({
        name: 'peoples',
        nancy: IPeople, // error at this line
      })

    export default Peoples;
Bashaw answered 16/10, 2018 at 5:30 Comment(0)
D
20

There's no way to go from a TypeScript type declaration to a mobx-state-tree model definition (except maybe via metadata reflection, though I doubt anyone has implemented that). However, if you write the mobx-state-tree model definition, then you can generate the TypeScript type from it; see Using a MST type at design time in the readme. So you would have to convert your existing interfaces, but at least you wouldn't have to keep maintaining two copies of the same information.

import { types, Instance } from 'mobx-state-tree';

const Person = types.model({
  name: types.string,
  age: types.number
});
export type IPeople = Instance<typeof Person>;

const Peoples = types
  .model({
    name: 'peoples',
    nancy: Person
  })

export default Peoples;
Dissimilar answered 16/10, 2018 at 6:13 Comment(4)
How would you hide private members from the interface generated with help of Instance?Uptown
May be you can try SnapshotOut<typeof Person>.Sech
@Bashaw then you will have all of your references unresolvedCoordinate
random extra note if you have a factory function returning a state model e.g. function generatePerson() { types.model({ name: 'person' }) } then you can get the state model with ReturnType<typeof generatePerson> (and then Instance<ReturnType<typeof generatePerson>> for an instance of that model)Stearn

© 2022 - 2024 — McMap. All rights reserved.