Skip to content

Refinement and validation - where are docs? #2261

Answered by coolsoftwaretyler
OnkelTem asked this question in Q&A
Discussion options

You must be logged in to vote

Hey @OnkelTem - yeah sorry about the docs. Does this example help?

import { types } from "mobx-state-tree";

const GrossWeightModel = types.model({
  gross: types.number,
  tareWeight: types.number,
});

const NetWeightModel = types.model({
  net: types.number,
});

// Refinement to enforce `gross > tareWeight`
const ValidWeight = types.refinement(
  types.union(NetWeightModel, GrossWeightModel),
  (weight) => {
    if ("gross" in weight) {
      return weight.gross > weight.tareWeight;
    }
    return true; // Net weight model is always valid
  }
);

const ProductWeightModel = types.model({
  weight: ValidWeight,
});

const validProduct = ProductWeightModel.create({
  weight: { gross: 10, 

Replies: 1 comment 3 replies

Comment options

You must be logged in to vote
3 replies
@OnkelTem
Comment options

@OnkelTem
Comment options

@OnkelTem
Comment options

Answer selected by OnkelTem
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants