`types.compose` 不会覆盖快照要求的基本属性。

作者: kylemeenehan创建于 2025年3月17日更新于 2025年3月17日
标签help/PR welcomelevel: easydocs or examples

**_错误报告_** - [x] 我已经检查了文档并搜索了现有问题和讨论(https://GitHub.com/mobxjs/mobx-state-tree/discussions) - [x] 我确保我的项目基于最新的 MST 版本 - [x] 我fork了此代码沙箱(https://codesandbox.io/p/sandbox/mobx-state-tree-todolist-forked-pj732k)或另一个最小的重现代码。 **沙箱链接或最小的重现代码** - [link to your sandbox or alternatively minimal reproduction code] https://codesandbox.io/p/sandbox/dpzr23 **描述预期行为** - [什么应该发生?] 使用 `types.compose` 时,我希望子对象的属性覆盖其父对象的属性。在之前的 MST 版本中,这似乎是可行的,但在最新版本中似乎不是。 **描述观察到的行为** - [什么情况发生了?] 给定以下代码: import { types } from "mobx-state-tree"; enum Invariant { A = 'A', B = 'B' } const Base = types.model({ name: types.string, invariant: types.enumeration(Object.values(Invariant)) }); const TypeA = types.compose(Base, types.model('TypeA', { invariant: Invariant.A })); const TypeB = types.compose(Base, types.model('TypeB', { invariant: types.literal(Invariant.B) })); const a = TypeA.create({ name: 'Such a great name' }); const b = TypeB.create({ name: 'An even better name' }); 我希望在创建 `TypeA` 或 `TypeB` 的实例时,`invariant` 属性不必填写。然而,TypeScript 会报错并表示向 `TypeA.create` 和 `TypeB.create` 提供的快照不合法。以下是来自代码沙箱重现的错误: Argument of type '{ name: string; }' is not assignable to parameter of type 'string | ModelCreationType<{ name: string; invariant: string; }> | undefined'. Type '{ name: string; }' is not assignable to type 'ModelCreationType<{ name: string; invariant: string; }>'. Property 'invariant' is missing in type '{ name: string; }' but required in type '{ name: string; invariant: string; }'.TypeScript(2345) 正如我上面所说的,我认为这是一个回退。但是,请让我知道我是否忽略了最近的设计决策变化或误解了任何文档。感谢您提供了一个伟大的库!如果我有时间,我可能会尝试研究一下这个问题,但目前我有点忙。

内容来源: mobxjs/mobx-state-tree