mobx-state-tree
mobx-state-tree copied to clipboard
Optional default gets a Typescript complaint
Bug report
When declaring an optional default for a model with entirely defaultable properties, I get a typescript error that I haven't been able to figure out.
- [x] I've checked documentation and searched for existing issues
- [x] I've made sure my project is based on the latest MST version
- [x] Fork this code sandbox or another minimal reproduction.
Sandbox link or minimal reproduction code https://codesandbox.io/s/optionaldefaultproblem-qx08w
import { types } from "mobx-state-tree";
export const ChildModel = types.model("Child").props({
flag: types.maybe(types.boolean)
});
export const StoreModel = types.model("Store").props({
child: types.optional(ChildModel, {}) // red squiggly under `{}` with error below
});
Describe the expected behavior
Before I discovered this problem when upgrading a project from much older mobx (4.2.1) & mobx-state-tree (2.0.5) versions, this worked: I could initialize MST models with naked-object snapshots and leave out maybe
or optional
properties if I wanted.
Describe the observed behavior If I don't specify values for all the properties when building the snapshot object to use as the default, Typescript complains:
Argument of type '{}' is not assignable to parameter of type 'OptionalDefaultValueOrFunction<IModelType<{ flag: IMaybe<ISimpleType<boolean>>; }, {}, _NotCustomized, _NotCustomized>>'.
Type '{}' is not assignable to type '() => ExtractCSTWithSTN<IModelType<{ flag: IMaybe<ISimpleType<boolean>>; }, {}, _NotCustomized, _NotCustomized>>'.
Type '{}' provides no match for the signature '(): ExtractCSTWithSTN<IModelType<{ flag: IMaybe<ISimpleType<boolean>>; }, {}, _NotCustomized, _NotCustomized>>'.ts(2345)
I get essentially the same error if I define ChildModel's flag
as types.optional(types.boolean, false)
(or just false
, which is the same thing, right?).
If I do child: types.optional(ChildModel, { aProp: false })
instead (with either declaration, optional
or maybe
), the error goes away.
Might be related to this? https://github.com/mobxjs/mobx-state-tree/pull/1269
I think its related to #1307
@bryanstearns, please check your tsconfig
. The compiler flags should be like:
{
"strict": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"noImplicitAny": true,
"noFallthroughCasesInSwitch": true,
"noImplicitReturns": true,
"noImplicitThis": true
}
(please note that sandbox might not pick up compiler flag changes from my experience, so best test it locally or on stackblitz)
Any update on this ?