typescript - 如何用 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;
解决方案
没有办法从 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;
推荐阅读
- c - 为什么这个程序会无限循环?
- jquery - contenteditable - 使用 jquery 更新 data-* 属性
- mongodb - 无论如何都无法连接到 Mongo Atlas
- java - Stringbuilder 检查字符串但跳过该字符串并返回其他字符串
- android - RecyclerView 在 android espresso 测试中不滚动
- c# - Unity3D:添加 Vector3 会导致错误的值
- android - 使用本地 HTML 在 Android 上加载本地文件 - net::ERR_FILE_NOT_FOUND
- swift - Alamofire 请求是否真的在后台线程中运行?
- digital-signature - 如何在比特币交易中验证数字签名?
- java - 有没有办法让 Gradle 测试结果转到一个 xml 文件?