最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to have a nullable string value in Mobx-State-Tree - Stack Overflow

programmeradmin0浏览0评论

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).

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).

Share Improve this question asked Aug 14, 2018 at 11:45 AbsoluteSithAbsoluteSith 1,96725 silver badges61 bronze badges 0
Add a comment  | 

3 Answers 3

Reset to default 15

You can use types.maybeNull to have a type that can also be null.

hint: types.maybeNull(types.string)

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

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));
}
发布评论

评论列表(0)

  1. 暂无评论