Variable models are a Typesaurus feature that allows defining a collection with a few different types instead of a single one.
Let’s say you have a collection of accounts of different types, e.g., GitHub, Microsoft, and Google. You can define a variable model like this:
Typesaurus recognized that you’re trying to set a GitHub account and type-checked the userId field.
Reading
When you read a variable document, you’ll have access to all fields, but unique fields will be optional until you check for the type:
It differs from union behavior, where you would have to check for the property existence before accessing it:
Updating
Setting and reading variable documents is pretty straightforward. However, it gets trickier when you want to update it.
Variable collections prevent you from updating the document without ensuring it’s of the right shape using the narrow, so you can’t accidentally update the wrong type:
However, you still can update fields that are shared between types:
That forces you to always read variable documents before updating them, but it is the only way to ensure you don’t accidentally update the wrong kind and cause runtime errors.
Why not unions?
You might ask, why not to use union instead:
The main problem is that it’s not possible to get shared shape where the field types are compatible, opening the door for bugs:
Another inconvenience is that you must check for the property’s existence before accessing it, making the rendering logic more complex.
All in all, variable models are a more robust solution for modeling documents with different shapes and allow Typesaurus have to better control over the schema