TypeScript中Mobx-State-Tree结合Yup使用SchemaOf匹配SnapshotOut报错问题
报错根本原因
- MobX-State-Tree 生成的
SnapshotOut、Instance属于带特殊标记的 branded 类型,没有内置索引签名,不满足 YupObjectShape泛型约束 - Yup v1+ 对对象 schema 的字段校验更严格,会识别到 MST 注入的隐藏类型标记(比如报错中的
[$nonEmptyObject]),导致类型匹配失败
解决方案1:类型断言(快速适配,适合小场景)
直接在 schema 定义末尾加类型断言,绕开YUP的严格类型校验,只要确保schema字段和MST快照字段完全对应,运行时和类型安全都不会有问题:
const userNameSchema = yup.object({ name: yup.string().required().defined().min(3), }) as SchemaOf<UserNameModelSnapshot>;
解决方案2:先定义纯业务接口再同步类型(更规范,适合长期维护项目)
先写普通TS接口作为单源类型,分别同步给MST和Yup,从根源避免类型不兼容问题:
// 1. 定义纯业务接口,天然符合Yup的类型要求 interface IUser { name: string; } // 2. 定义MST模型,加校验保证和接口字段一致 const UserNameModel = types.model({ name: types.string, }); // 类型校验:如果接口和MST字段不匹配,这一行会直接报错 type AssertEqual<T, U> = T extends U ? U extends T ? true : false : false; const _typeCheck: AssertEqual<IUser, SnapshotOut<typeof UserNameModel>> = true; // 3. 定义Yup schema,无任何类型报错 const userNameSchema: SchemaOf<IUser> = yup.object({ name: yup.string().required().defined().min(3), });
解决方案3:清洗MST生成的类型(不想单独定义接口时用)
用TS映射类型把MST类型的特殊标记清除,转成普通对象类型再给Yup用:
// 清洗Snapshot类型,移除MST注入的隐藏标记 type PureUserSnapshot = { [K in keyof SnapshotOut<typeof UserNameModel>]: SnapshotOut<typeof UserNameModel>[K] }; const userNameSchema: SchemaOf<PureUserSnapshot> = yup.object({ name: yup.string().required().defined().min(3), });
内容的提问来源于stack exchange,提问作者ridermansb
相关产品推荐
相关产品推荐

