Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
like image 571
马邦德 Avatar asked Nov 29 '22 21:11

马邦德


1 Answers

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;
like image 142
Matt McCutchen Avatar answered May 21 '23 07:05

Matt McCutchen