Skip to content

Types of an types.model narrowed from a union with a literal don't have actions? #1975

Answered by davidatsurge
davidatsurge asked this question in Q&A
Discussion options

You must be logged in to vote

So, it turns out the following works (ie, doesn't trip up typescript), and it fulfills my desire to "make illegal states unrepresentable", and it follows the more standard pattern of "tagged unions" anyways:

const Bed = types.model({}).actions((self) => ({
  addBlankets() {
    // adding blankets
  },
}));

const Room = types
  .model({
    bed: types.union(
      types.model({status: types.literal("loading")}),
      types.model({status: types.literal("loaded"), item: Bed})
    )
  })
  .actions((self) => ({
    addBlanketsOnBed() {
      if (self.bed.status != "loading") {
        self.bed.item.addBlankets();
      }
    },
  }));

Replies: 2 comments 3 replies

Comment options

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

@antondomratchev
Comment options

@davidatsurge
Comment options

Comment options

You must be logged in to vote
0 replies
Answer selected by davidatsurge
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