如何用 typescript 接口描述 mobx-state-tree 的模型?
How to describe model of mobx-state-tree with interface of typescript?
我已经有了一些接口,我想用这些接口来描述模型,就像下面的代码一样。否则我必须使用 mobx-state-tree
的 types
再写一遍。但这不是正确的方法,什么是有效的解决方案?
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;
没有办法从 TypeScript 类型声明到 mobx-state-tree
模型定义(除了可能通过元数据反射,但我怀疑有人已经实现了)。但是,如果您编写 mobx-state-tree
模型定义,则可以从中生成 TypeScript 类型;请参阅自述文件中的 Using a MST type at design time。所以你将不得不转换你现有的接口,但至少你不必继续维护相同信息的两个副本。
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;
我已经有了一些接口,我想用这些接口来描述模型,就像下面的代码一样。否则我必须使用 mobx-state-tree
的 types
再写一遍。但这不是正确的方法,什么是有效的解决方案?
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;
没有办法从 TypeScript 类型声明到 mobx-state-tree
模型定义(除了可能通过元数据反射,但我怀疑有人已经实现了)。但是,如果您编写 mobx-state-tree
模型定义,则可以从中生成 TypeScript 类型;请参阅自述文件中的 Using a MST type at design time。所以你将不得不转换你现有的接口,但至少你不必继续维护相同信息的两个副本。
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;