如何用打字稿的界面描述mobx-state-tree的模型?

马邦德*_*马邦德 3 typescript mobx mobx-state-tree

我已经有了一些接口,我想用这个接口来描述模型,就像下面的代码一样.否则,我必须通过再次使用写typesmobx-state-tree.但这不是正确的方法,什么是有效的解决方案?

    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;
Run Code Online (Sandbox Code Playgroud)

Mat*_*hen 16

没有办法从TypeScript类型声明转到mobx-state-tree模型定义(除非可能通过元数据反射,但我怀疑是否有人实现了这一点).但是,如果编写mobx-state-tree模型定义,则可以从中生成TypeScript类型; 请参阅自述文件中设计时使用MST类型.因此,您必须转换现有的接口,但至少您不必继续维护相同信息的两个副本.

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;
Run Code Online (Sandbox Code Playgroud)