首页 > 解决方案 > mobx state tree: if wrong type, discard value and use default instead of throwing an error

问题描述

In mobx state tree, if the type is wrong, it throws an error. Is there a way to make it not throw an error, and just discard the value and use a default? (types.optional works for a predefined set, but not any value of the wrong type.)

Setup

const TestModel = types.model({
  testProp: "",
})

const testModel = TestModel.create({
  testProp: 5 // or null, [], 9, undefined, etc
})

Desired

console.log(testModel.testProp) // ""

Actual

// Error thrown.

Basically I want to guarantee the type of inconsistent server data so I don't have to ?. everywhere.

标签: javascriptmobx-state-tree

解决方案


推荐阅读