javascript - 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.
解决方案
推荐阅读
- javascript - 如何为一系列 JavaScript if 语句创建后备?
- java - 如何将 Unix 时间戳(以毫秒为单位)转换为与 PostgreSQL 兼容的时间戳?
- c++ - 一个自包含的 C++ 概念可以匹配一个带有任何参数的特定模板吗?
- r - R - 找不到函数“dashboardPagePlus”
- arrays - “while(!x && i < n)”中的“!x”是什么意思
- javascript - 以适当的方式在 react rest-hooks 库中使用突变时如何反映缓存中的变化
- kotlin - Kotlin 集合:indexOfFirst 与 find
- apache-kafka - 使用来自主题的最新消息并忽略所有先前发布的消息
- php - 在 add_action 函数中使用参数
- contentful - 有没有办法获取内容类型的数据(下拉数据)?