【问题标题】:mobx-state-tree convert optional type to non-optionalmobx-state-tree 将可选类型转换为非可选
【发布时间】:2019-01-17 11:46:31
【问题描述】:

如何将可选类型转换为非可选

types.optional(types.string)types.optional 据我所知,这是可行的:

const t = optional(types.string); 
delete t.defaultValue

但这似乎非常错误。有没有更好的办法?

【问题讨论】:

  • 哎哟......这大错特错。请解释一下为什么您甚至希望将可选转换为非可选?
  • 这是我需要从现有模型声明动态构建新模型的情况。此外,我想构建一个相同的模型类型并将所有道具设置为可能类型。 Maybe 类型和 optional 类型不能很好地结合在一起,因为 undefined 总是会回退到 optional 的默认值。用例是一个表单组件,它将包含未定义的值并在输入时验证这些属性

标签: mobx-state-tree


【解决方案1】:

您可以使用.named(name) 方法,该方法克隆给定类型,给它一个新的name,并为您提供一种“扩展”它的方法,包括附加属性、视图、操作,或者可能是那些声明的覆盖在原始类型中。

例子:

const Square = types
    .model("Square",
        {
            width: types.number
        }
    )
    .views(self => ({
        surface() {
            return self.width * self.width
        }
    }))

// create a new type, based on Square
const Box = Square
    .named("Box")
    .views(self => {
        // save the base implementation of surface
        const superSurface = self.surface

        return {
            // super contrived override example!
            surface() {
                return superSurface() * 1
            },
            volume() {
                return self.surface * self.width
            }
        }
    }))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-24
    • 2019-11-26
    • 2021-04-25
    • 2019-09-05
    • 2018-06-17
    • 2018-10-06
    相关资源
    最近更新 更多