-
I have the following type: type Foo = {
name: string
height?: number
} and I want to create objects of that type: In addition, I would want to get some default for But currently I can't get anything of that working, and here is why. import { Instance, types } from 'mobx-state-tree'
type Foo = {
name: string
height?: number
}
const FooModel1 = types.model('Foo', {
name: types.string,
height: types.optional(types.number, 0),
})
type FooType1 = Instance<typeof FooModel1>
const foo1: FooType1 = {
name: 'John',
}
/* ERROR:
Type '{ name: string; }' is not assignable to type 'ModelInstanceTypeProps<{ name: ISimpleType<string>; height: IOptionalIType<ISimpleType<number>, [undefined]>; }> & IStateTreeNode<...>'.
Property 'height' is missing in type '{ name: string; }' but required in type 'ModelInstanceTypeProps<{ name: ISimpleType<string>; height: IOptionalIType<ISimpleType<number>, [undefined]>; }>'.(2322)
*/ The Now let's switch to import { Instance, types } from 'mobx-state-tree'
type Foo = {
name: string
height?: number
}
const FooModel2 = types.model('Foo', {
name: types.string,
height: types.maybe(types.number),
})
type FooType2 = Instance<typeof FooModel2>
const foo2_1: FooType2 = {
name: 'John',
}
/* ERROR:
Type '{ name: string; }' is not assignable to type 'ModelInstanceTypeProps<{ name: ISimpleType<string>; height: IMaybe<ISimpleType<number>>; }> & IStateTreeNode<IModelType<{ name: ISimpleType<string>; height: IMaybe<...>; }, {}, _NotCustomized, _NotCustomized>>'.
Property 'height' is missing in type '{ name: string; }' but required in type 'ModelInstanceTypeProps<{ name: ISimpleType<string>; height: IMaybe<ISimpleType<number>>; }>'.(2322)
*/
const foo2_2: FooType2 = {
name: 'John',
height: undefined
} So I still can't create Any clues? Maybe I should use |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
First, I'll cover the three main types for MST models:
Second, here's what the docs say about optional types:
A bit implicit, but the optionality is on the input, not the instance/output. This means that So that's for the first part. The second part is
So the problem here is that you're trying to coerce a POJO into an instance of I believe Let me know if you have any more questions, and whether or not there's something you think we could do to make all of this clearer. |
Beta Was this translation helpful? Give feedback.
First, I'll cover the three main types for MST models:
SnapshotIn
is the input type needed byMyModelType.create
to construct an instanceInstance
is an instance of an MST type. You can usually assign an MST instance into an interface with simple javascript types, but a plain old javascript object (POJO) usually can't be assigned to an MST instance type (as you noticed, and we'll discuss below).SnapshotOut
the type ofgetSnapshot(instance)
Second, here's what the docs say about optional types: