首页 > 解决方案 > 如何用 typescript 的接口描述 mobx-state-tree 的模型?

问题描述

我已经有了一些接口,我想用这些接口来描述模型,就像下面的代码一样。types否则我必须使用of再次编写mobx-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;

标签: typescriptmobxmobx-state-tree

解决方案


没有办法从 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;

推荐阅读