Reputation: 1967
I'm trying to create a model with a optional, nullable string value. I've tried using both
hint: types.optional(types.string, ""),
and
hint: types.maybe(types.string),
Both results in error when I try to set a json object as to the object. Works if I manually loop through the json object and set the null content to empty string "".
Error while converting "jsoncontent" at path "content" value
null
is not assignable to type:string
(Value is not a string).
Upvotes: 5
Views: 5139
Reputation: 41
I have created a helper function that allows you to simultaneously have optional and nullable types.
function nullOrUndefined<T extends IAnyType>(type: T) {
return types.maybe(types.maybeNull(type));
}
Upvotes: 0
Reputation: 112807
You can use types.maybeNull
to have a type that can also be null
.
hint: types.maybeNull(types.string)
Upvotes: 15
Reputation: 3182
You can use one of the following solutions to have a nullable string value in a Mobx-State-Tree:
types.maybeNull(types.string) // value can be null
or
types.optional(types.string, '') // should create empty string if value is not defined
Upvotes: 3