`mobx-keystone` gives you MobX-powered, TypeScript-first state trees: a single source of truth, mutable model code, and immutable traceability built in.
## Quick glance
Straightforward models. Explicit actions. Reactive state.
```ts title="Todo.ts"
@model("todo/Todo")
class Todo extends Model({
text: prop(""),
done: prop(false),
}) {
@modelAction
toggle() {
this.done = !this.done
}
}
@model("todo/Store")
class TodoStore extends Model({
todos: prop(() => []),
}) {
@computed
get pendingCount() {
return this.todos.filter((t) => !t.done).length
}
@modelAction
addTodo(text: string) {
this.todos.push(new Todo({ text }))
}
}
const store = new TodoStore({})
registerRootStore(store)
```
You write straightforward actions and computed values, while the library gives you snapshots, patches, undo/redo, and runtime protection on top. You can think of it as a TypeScript-first model layer on top of MobX that scales better as your domain grows.
## Why teams choose mobx-keystone
- Mutable action code with protected updates, so state changes stay explicit and safe.
- Runtime snapshots and JSON patches for persistence, sync, replay, and debugging.
- Built-in primitives for references, transactions, action middlewares, and undo/redo.
- Optional [Y.js](./integrations/yjsBinding.mdx) and [Loro](./integrations/loroBinding.mdx) bindings for collaborative, offline-friendly state.
- Strong TypeScript inference for models, snapshots, and actions.
- Composable domain models that stay maintainable as app complexity grows.
- Seamless integration with MobX and `mobx-react-lite`.
## Choose your starting point
[**Getting Started →**Set up a first store in a real app.](./gettingStarted.mdx)
[**Class Models →**The main model style for app state.](./classModels.mdx)
[**Data Models →**Backend-shaped data without `$modelType`.](./dataModels.mdx)
[**Root Stores →**App life-cycle and where side effects belong.](./rootStores.mdx)
[**Snapshots →**Immutable, serializable views of any part of the tree.](./snapshots.mdx)
[**Coming from MST? →**Concepts, terminology and a step-by-step migration.](./mstMigrationGuide.mdx)
## See it running
Each example is a working app running right in the page, with its full source below it.
[**Todo List →**A complete app with live logs of its actions, patches and snapshots.](./examples/todoList/todoList.mdx)
[**Client/Server →**Two clients kept in sync through a server by replaying actions.](./examples/clientServer/clientServer.mdx)
[**Y.js Binding →**Two replicas of the same store, synced as a Y.js CRDT over WebRTC.](./examples/yjsBinding/yjsBinding.mdx)
[**Loro Binding →**Two replicas of the same store, synced as a Loro CRDT in the browser.](./examples/loroBinding/loroBinding.mdx)
## How it works
At the center of `mobx-keystone` is a _living tree_ of mutable but strictly protected models, arrays, and plain objects. You update state through model actions, and immutable structurally shared snapshots are derived automatically.
This gives you mutability where it helps developer experience, plus immutable traceability where it helps reliability.
Trees can only be modified by actions that belong to the same subtree. Actions are replayable and can be distributed, and fine-grained changes can be observed as JSON patches.
Because `mobx-keystone` uses MobX behind the scenes, it integrates naturally with [`mobx`](https://mobx.js.org) and [`mobx-react-lite`](https://github.com/mobxjs/mobx/tree/main/packages/mobx-react-lite). The snapshot and middleware system also makes it possible to replace a Redux reducer/store pair with model-driven state and connect Redux devtools.
`mobx-keystone` consists of composable _models_ that capture domain state and behavior together. Model instances are created from props, protect their own updates, and reconcile efficiently when applying snapshots.
---
# installation
This page is only about setup: install the packages, choose your decorator mode, and make sure your toolchain is configured correctly.
If you want to build a first working store after setup, continue with [Getting Started](./gettingStarted.mdx).
**npm**
```bash
npm install mobx mobx-keystone
```
**pnpm**
```bash
pnpm add mobx mobx-keystone
```
**yarn**
```bash
yarn add mobx mobx-keystone
```
`mobx-keystone` requires `mobx` as a peer dependency, so both packages need to be installed.
When using TypeScript, version 5.4 or newer is required.
If you are using React, add `mobx-react-lite` too:
**npm**
```bash
npm install mobx-react-lite
```
**pnpm**
```bash
pnpm add mobx-react-lite
```
**yarn**
```bash
yarn add mobx-react-lite
```
This library requires a modern JavaScript environment with support for:
- MobX 7, 6, 5 (or 4 with its gotchas)
- Proxies
- Symbols
- WeakMap/WeakSet
In practice, this covers current browsers and Node.js releases, but not Internet Explorer.
If you are using TypeScript:
- Version 5.0+ is recommended (standard decorators).
- `mobx-keystone` decorators also support the legacy transform (`experimentalDecorators: true`).
MobX 7 itself no longer supports legacy decorators. When using MobX 7, choose the standard
decorator transform for code that uses MobX decorators such as `@computed`, `@action`, or
`@observable`.
## Setup checklist
Before writing your first model, make sure your app setup matches these assumptions:
- `mobx` is installed next to `mobx-keystone`.
- Your TypeScript / Babel / SWC config consistently uses either standard decorators or legacy decorators.
- If your app has a long-lived application store, registering it as a root store is recommended.
- Your UI layer uses a MobX binding such as `mobx-react-lite` if you want React components to observe model changes.
## Transpiler configuration
This library uses JavaScript decorators and class properties.
### Standard decorators
Use this mode if you want standard decorators.
For Babel, ensure class static blocks are transformed (for example via `@babel/preset-env` targets, or by adding `@babel/plugin-transform-class-static-block`).
**TypeScript**
```jsonc title="tsconfig.json"
{
"compilerOptions": {
"experimentalDecorators": false,
"useDefineForClassFields": true
}
}
```
**Babel**
```jsonc title="babel.config.json"
{
"presets": [
["@babel/preset-typescript", { "allowDeclareFields": true }], // if using TypeScript
["@babel/preset-env"]
],
"plugins": [
["@babel/plugin-proposal-decorators", { "version": "2023-11" }],
["@babel/plugin-proposal-class-properties", { "loose": false }]
]
}
```
**SWC**
```jsonc title=".swcrc"
{
"jsc": {
"parser": {
"syntax": "typescript", // or "ecmascript" for JavaScript
"decorators": true
},
"transform": {
"decoratorVersion": "2022-03",
"useDefineForClassFields": true
},
"loose": false
}
}
```
### Legacy decorators
Use this mode if your project is on legacy decorators (`experimentalDecorators: true`).
This mode remains supported by `mobx-keystone` decorators. MobX 7's own decorators cannot
be used in this mode; choose the standard decorator configuration above if your code uses
them.
**TypeScript**
```jsonc title="tsconfig.json"
{
"compilerOptions": {
"experimentalDecorators": true,
"useDefineForClassFields": true
}
}
```
**Babel**
```jsonc title="babel.config.json"
{
"presets": [
["@babel/preset-typescript", { "allowDeclareFields": true }] // if using TypeScript
],
"plugins": [
["@babel/plugin-proposal-decorators", { "version": "legacy" }],
["@babel/plugin-proposal-class-properties", { "loose": false }]
]
}
```
**SWC**
```jsonc title=".swcrc"
{
"jsc": {
"parser": {
"syntax": "typescript", // or "ecmascript" for JavaScript
"decorators": true
},
"transform": {
"legacyDecorator": true // required for JavaScript, optional for TypeScript
},
"loose": false
}
}
```
## Next step
Once installation and transpiler setup are done, move on to [Getting Started](./gettingStarted.mdx) for the first working store.
---
# gettingStarted
This guide takes you from an empty project to a small working `mobx-keystone` store connected to React.
Before starting here, finish [Installation](./installation.mdx) so `mobx`, `mobx-keystone`, and your decorator/transpiler setup are already in place.
If you are still deciding between model styles, start with [Class Models](./classModels.mdx). They are the most direct fit for application state.
## 1. Define your domain models
Create models for the state you want to keep live in your app. The example below uses class models, model actions, and MobX computed values.
```ts title="store.ts"
@model("todo/Todo")
export class Todo extends Model({
id: idProp, // auto-generated unique id, accessible as `$modelId`
text: prop(""),
done: prop(false),
}) {
@modelAction
toggle() {
this.done = !this.done
}
}
@model("todo/Store")
export class TodoStore extends Model({
todos: prop(() => []),
}) {
@computed
get pendingCount() {
return this.todos.filter((todo) => !todo.done).length
}
@modelAction
addTodo(text: string) {
this.todos.push(new Todo({ text }))
}
}
export function createTodoStore() {
const store = new TodoStore({})
registerRootStore(store)
return store
}
```
Why register the root store?
- It enables `onAttachedToRootStore`.
- It makes `getRootStore(...)` work.
- It establishes this tree as the live boundary of your application state.
- It gives models a reliable place to start and dispose app-wide side effects.
Registration is recommended for a long-lived application store, but it is not required to create models, take snapshots, or attach middleware to a tree.
## 2. Render the store in React
Use `observer` so the component re-renders when observable model data changes.
```tsx title="App.tsx"
export const App = observer(() => {
const [store] = useState(() => createTodoStore())
const [text, setText] = useState("")
return (
Todos
Pending: {store.pendingCount}
{store.todos.map((todo) => (
))}
)
})
```
## 3. Know the core ideas
`mobx-keystone` feels easier once you know which primitive solves which problem:
| Need | Use |
| --- | --- |
| Mutable domain objects with actions and hooks | [Class Models](./classModels.mdx) |
| Backend-shaped data without `$modelType` in the payload | [Data Models](./dataModels.mdx) |
| Async actions | [Standard and Standalone Actions](./standardAndStandaloneActions.mdx) |
| App-level lifecycle and side effects | [Root Stores](./rootStores.mdx) |
| Serialization and persistence | [Snapshots](./snapshots.mdx) |
| Fine-grained change streams | [Patches](./patches.mdx) |
| Runtime validation | [Runtime Type Checking](./runtimeTypeChecking.mdx) |
## 4. Recommended next steps
Once the basic store is running, the next guides usually depend on what you need next:
- Want a deeper model walkthrough? Read [Class Models](./classModels.mdx).
- Need to persist or hydrate state? Read [Snapshots](./snapshots.mdx).
- Want undo/redo or interception? Read [Action Middlewares](./actionMiddlewares/undoMiddleware.mdx).
- Need references between entities? Read [References](./references.mdx).
- Prefer learning from a complete example? Open the [Todo List Example](./examples/todoList/todoList.mdx).
---
# classModels
## Overview
`mobx-keystone` supports the following kinds of data:
- Class models, which combine observable data with local behavior (actions/views) and life-cycle hooks.
- Data models, which define behavior over plain, untagged data and have only a limited life-cycle hook.
- Plain objects, which store structured data or act as key-value maps without model behavior or hooks.
- Arrays.
- Primitive values (`string`, `boolean`, `number`, `null`, `undefined`).
In this section we will focus on class models, since the other types can be used as children in the usual way.
Class models and data models provide `toString({ withData? })` for a string representation. Data is included by default, including when `withData` is `undefined`; pass `false` to omit it.
## Your first class model
A class model is a class decorated with `@model(...)` that extends `Model({ ... })`:
- The string passed to `@model` identifies the model type in snapshots, so it must be unique across your whole application.
- The properties passed to `Model` are the model data: observable, part of snapshots and patches, and required when creating an instance unless they have a default.
- Methods decorated with `@modelAction` are the only place where model data can change. Being actions also gives them middlewares, replication, and the other action features.
- Views are regular getters, usually decorated with MobX's `@computed`.
Properties can be declared with `prop` (TypeScript types only) or with `tProp` (TypeScript types plus runtime type checking):
**prop**
```ts title="Todo.ts"
@model("myCoolApp/Todo")
export class Todo extends Model({
text: prop(), // required
done: prop(false), // defaults to `false`
}) {
@modelAction
setDone(done: boolean) {
this.done = done
}
@modelAction
setText(text: string) {
this.text = text
}
@computed
get asString() {
return `${!this.done ? "TODO" : "DONE"} ${this.text}`
}
}
```
To make a property truly optional, include `undefined` in its type: `x: prop()`.
**tProp**
```ts title="Todo.ts"
@model("myCoolApp/Todo")
export class Todo extends Model({
text: tProp(types.string), // required
done: tProp(types.boolean, false), // defaults to `false`
}) {
@modelAction
setDone(done: boolean) {
this.done = done
}
@modelAction
setText(text: string) {
this.text = text
}
@computed
get asString() {
return `${!this.done ? "TODO" : "DONE"} ${this.text}`
}
}
```
To make a property truly optional, use `types.maybe`: `x: tProp(types.maybe(types.string))`. See [runtime type checking](./runtimeTypeChecking.mdx) for all the available types.
### Property declarations
A default is used whenever the property is `null` or `undefined` in the creation data or the input snapshot.
| Without runtime type checking | With runtime type checking | Default |
| --- | --- | --- |
| `prop()` | `tProp(type)` | None. |
| `prop(defaultValue)` | `tProp(type, defaultValue)` | `defaultValue`. Use it for primitives only. |
| `prop(() => defaultValue)` | `tProp(type, () => defaultValue)` | The result of calling the function. Use it for objects, arrays, and models, so every instance gets its own copy. |
`tProp` also has two shorthands: `tProp("text")`, `tProp(0)`, and `tProp(false)` are the same as `tProp(types.string, "text")` and so on, and `tProp([typeA, typeB])` is the same as `tProp(types.or(typeA, typeB))`.
## Class model rules
- Decorate the class with `@model` and give the model type a unique application-wide name. An empty string is a valid name; in `decoratedModel`, only `undefined` means to omit registration.
- Extend `Model` with the properties that should be observable, snapshotable, and patchable.
- Access model data through either `this` or `this.$`.
- Change model data inside model actions.
:::warning No constructors
Do not declare a constructor in a class model. Use the [life-cycle hooks](#life-cycle-event-hooks) instead.
:::
Of course primitives are not the only kinds of data that a class model can hold. Arrays, plain objects and other objects can be used as well.
## Creating a class model instance
An instance of the todo model above can be created like this:
```ts
const myTodo1 = new Todo({ done: true, text: "buy some milk" })
// note how `done` can be skipped since it was declared with a default value
const myTodo2 = new Todo({ text: "buy some coffee" })
```
## Automatic class model actions for property setters
Most times, the only action we need for a property is a setter. We can use the prop modifier `withSetter()` (`withSetter("assign")` has been deprecated) to reduce boilerplate and generate property setters. For example, the model above could be written as:
```ts
@model("myCoolApp/Todo")
export class Todo extends Model({
text: prop().withSetter(),
done: prop(false).withSetter(),
}) {}
const myTodo = new Todo({ text: "buy some coffee" })
// this is now allowed and properly wrapped in two respective actions
myTodo.setText("buy some milk")
myTodo.setDone(true)
```
An empty-string property name generates a setter named `set`.
If you need to change data without declaring a custom `modelAction`, use the predefined `objectActions` or `arrayActions` helpers.
`withSetter` also accepts a value transform function. For example `withSetter(cloneTreeValue)` clones incoming non-primitive values before setting them, which is useful when the same object instance may be reused across different places in the tree. If you need clone options, wrap it (for example `withSetter((x) => cloneTreeValue(x, { generateNewIds: false }))`).
:::note
The transform function only runs in the generated setter (for example `model.setX(3)`). It does **not** run during model construction (`new Model({ x: 3 })`) or snapshot deserialization, where the value is assigned as provided.
:::
## Life-cycle event hooks
Class models can optionally include an implementation for each of the life-cycle hooks:
- `onInit()`, which serves as a replacement for the constructor and will fire as soon as the model is created.
On most occasions, it is better to use the next hook.
- `onAttachedToRootStore(rootStore)`, which fires once a class model becomes part of a root store tree and which can optionally return a disposer which will run once the model detaches from such root store tree.
It will be explained in detail in the [root stores](./rootStores.mdx) section.
## Runtime data
Runtime data that does not need to be snapshotted can be declared as a regular class property. Use MobX decorators when that runtime data also needs to be observable.
```ts
@model("myApp/SomeModel")
class SomeModel extends Model({
title: prop("demo"),
}) {
// non-observable runtime data
saveCount = 0
markSaved() {
this.saveCount++
}
// or observable in the usual MobX way
@observable
isSaving = false
@action
setSaving(isSaving: boolean) {
this.isSaving = isSaving
}
}
```
## Accessing the type and ID of a class model
Every class model includes a `$modelType` property:
```ts
myTodo1.$modelType // "myCoolApp/Todo"
```
This property ends up in the snapshot representation of the model and allows `fromSnapshot` to reconstruct the correct model class, so it is usually required.
There are two ways to omit `$modelType` from an input snapshot:
- If a property is typed using `tProp` then the model(s) in that property won't need `$modelType`.
- If a model is constructed using the `fromSnapshot` overload that takes a type as first parameter then that snapshot won't need `$modelType`.
### Runtime model registration (`registerModels`)
Most applications do not need to do anything special: importing and using model classes normally is enough for `@model(...)` decorators to register them.
You may need manual registration when your app mainly deserializes snapshots and some model imports are only used as TypeScript types (or otherwise elided by your build pipeline). In that case, `fromSnapshot` may fail with:
```txt
model with name "..." not found in the registry
```
To make registration explicit, call `registerModels(...)` once at app startup with runtime class references:
```ts
registerModels(RootStore, User)
```
This does not instantiate models; it only verifies the classes are loaded and registered.
## Setting an ID property
Note that it is also possible to assign a property as the ID property using `idProp`. Setting a dedicated ID property has some advantages:
- Improved reconciliation when applying snapshots.
- Resolving the target of serialized actions will be less likely to hit the wrong node (thanks to ID checking).
- Root references will be able to resolve the nodes without any extra configuration.
```ts
@model("myApp/ModelWithCustomId")
class ModelWithCustomId extends Model({
customId: idProp
}) {
...
}
```
In this case, use either `customId` (in snapshots and instances) or `$modelId` (in instances only) to read or write the ID.
The ID must be unique across all model objects in the same tree, regardless of model type.
An empty-string property name (`"": idProp`) also works as an ID field, including when cloning or reconciling snapshots.
Note that when using the `new` operator to create a new instance you can either not specify the property so it will be auto-generated, or you can specify it directly:
```ts
const myModel = new ModelWithCustomId({
customId: "my custom id",
})
```
as well as writing to it at a later time inside a model action:
```ts
// inside some model action
this.customId = "my new custom id"
// or alternatively
this.$modelId = "my new custom id"
```
If you wish to type the ID property even further (for example by using a string template) you may do it like this:
```ts
customId: idProp.typedAs<`custom-${string}`>()
```
## Customizing the ID generator function
The default model ID generator function is tuned up to be fast and works like this:
```ts
const baseLocalId = nanoid()
let localId = 0
function generateModelId() {
return localId.toString(36) + "-" + baseLocalId
}
```
This has the implications however that every model ID generated by the same client / server session will have a different first part of the ID, yet share the same last part of such ID.
That being said, it is possible to use a custom function to generate model IDs using `setGlobalConfig`:
```ts
setGlobalConfig({
modelIdGenerator: myModelIdGeneratorFunction,
})
```
You can also define a generator per model ID field using `idProp.withGenerator(...)`:
```ts
@model("myApp/Todo")
class Todo extends Model({
id: idProp.withGenerator(() => `todo-${uuid()}`),
text: prop(),
}) {}
```
For `ExtendedModel`, the generator follows inheritance:
- If base has one and extended does not override the id prop, extended uses base generator.
- If extended overrides a base id prop, `withGenerator(...)` must match the base one exactly (including `undefined`).
- If base has no id prop and extended defines one, extended uses its own generator.
## Getting the TypeScript types for model data and model creation data
- `ModelData` is the type of the model props without transformations (as accessible via `model.$`).
- `ModelCreationData` is the type of the first parameter passed to `new Model(...)`.
For example, given:
```ts
@model("myCoolApp/Todo")
export class Todo extends Model({
text: prop(), // a required string
done: prop(false), // an optional boolean that will default to `false`
}) {}
```
`ModelCreationData` would be:
```ts
{
text: string; // required when passing it to `new Todo({...})`
done?: boolean | null; // optional when passing it to `new Todo({...})`
}
```
and `ModelData` would be:
```ts
{
text: string // since it will always be present when accessing `todo.text`
done: boolean // since it will always be present when accessing `todo.done`
}
```
## Flows (async actions)
While `@modelAction` defines sync model actions, async model actions are possible as well with the use of `@modelFlow`. A flow is a generator function where `yield* _await(x)` takes the place of `await x`:
**TypeScript**
```ts
interface Book {
title: string
price: number
}
@model("myApp/BookStore")
class BookStore extends Model({
books: prop(() => []),
}) {
@modelFlow
fetchMyBooksAsync = _async(function* (this: BookStore, token: string) {
const myBooks = yield* _await(myBackendClient.getBooks(token))
this.books = myBooks
})
}
```
In TypeScript, wrap the generator in `_async` and type `this` as the class, so the flow is typed as returning a promise.
**JavaScript**
```js
@model("myApp/BookStore")
class BookStore extends Model({
books: prop(() => []),
}) {
@modelFlow
*fetchMyBooksAsync(token) {
const myBooks = yield* _await(myBackendClient.getBooks(token))
this.books = myBooks
}
}
```
In either case it is called like any async function:
```ts
const myBookStore = new BookStore({})
await myBookStore.fetchMyBooksAsync("someToken")
```
:::warning `yield*`, not `yield`
Always use `yield* _await(...)`. `_await` only works when delegated to with `yield*`, and a plain `yield` does not work. Both `_async` and `_await` are imported from `mobx-keystone`.
:::
## Value-type class models
Sometimes it is useful to have models that act like a primitive. This is, models that would get automatically cloned when attached to a tree rather than relying on having a single instance of it in the whole tree.
For example, say that you have a model for a RGB color:
```ts
@model("myApp/Color")
class Color extends Model(
{
r: prop(),
g: prop(),
b: prop(),
},
{
valueType: true,
}
) {}
```
Usually, without `valueType: true`, whenever we wanted to use the same color in two separate paths of the tree we would need to clone it first, or else we would get an error about the node trying to have two parents at once. With `valueType` set this would be no longer the case, since the node would get cloned automatically if it already had a parent:
```ts
@model("myApp/MyColors")
class MyColors extends Model({
primary: prop(),
secondary: prop(),
}) {
// ...
}
// without `valueType: true` this would throw an error
// but with it `primary` is now a clone of `secondary`
myColors.setPrimary(myColors.secondary)
```
Note that it is an actual clone, meaning changing the primary color won't change the secondary one.
## Factory pattern / Generics
If you are _not_ relying on `tProp` to do runtime type checking it is possible to use this pattern to get generic classes:
```ts
@model("myApp/GenericPoint")
class GenericPoint extends Model(() => ({
x: prop(),
y: prop(),
})) {
@modelAction
setXY(x: T, y: T) {
this.x = x
this.y = y
}
}
@model("myApp/Generic3dPoint")
class Generic3dPoint extends ExtendedModel(() => ({
baseModel: modelClass>(GenericPoint),
props: {
z: prop(),
},
})) {
// ...
}
```
If you rely on `tProp` (and also `prop` really) a different possibility is to use a factory pattern with class models. For example:
```ts
function createModelClass(modelName: string, initialX: TX, initialY: TY) {
@model(`myApp/${modelName}`)
class MyModel extends Model({
x: prop(() => initialX),
y: prop(() => initialY),
}) {
@modelAction
setXY(x: TX, y: TY) {
this.x = x
this.y = y
}
}
return MyModel
}
const NumberMyModel = createModelClass("NumberMyModel", 10, 20)
type NumberMyModel = InstanceType
const numberMyModelInstance = new NumberMyModel({}) // this will be of type `NumberMyModel`
numberMyModelInstance.setXY(50, 60)
const StringMyModel = createModelClass("StringMyModel", "10", "20")
type StringMyModel = InstanceType
const stringMyModelInstance = new StringMyModel({}) // this will be of type `StringMyModel`
stringMyModelInstance.setXY("50", "60")
```
Note that the above will only work when not generating declaration maps. If you need to generate declarations (for example for a library) then it is a bit more tedious, but still possible:
```ts
export function createModelClass(modelName: string, initialX: TX, initialY: TY) {
const MyModelProps = Model({
x: prop(() => initialX),
y: prop(() => initialY),
})
@model(`myApp/${modelName}`)
class MyModel extends MyModelProps {
@modelAction
setXY(x: TX, y: TY) {
this.x = x
this.y = y
}
}
return MyModel as ModelClassDeclaration<
typeof MyModelProps,
{
setXY(x: TX, y: TY): void
}
>
}
```
## Inheritance
Model inheritance is possible with a few gotchas.
The first thing to bear in mind is that class models that extend from other class models must use `ExtendedModel` rather than the plain `Model`. For example:
```ts
@model("MyApp/Point")
class Point extends Model({
x: prop(),
y: prop(),
}) {
get sum() {
return this.x + this.y
}
}
// note how `ExtendedModel` is used
@model("MyApp/Point3d")
class Point3d extends ExtendedModel(Point, {
z: prop(),
}) {
get sum() {
return super.sum + this.z
}
}
```
:::warning Call `super` in life-cycle hooks
If your base model has `onInit` / `onAttachedToRootStore` and you redeclare them in your extended model, call `super.onInit(...)` / `super.onAttachedToRootStore(...)` from the extended model.
:::
When extending a generic class, use `modelClass` to specify the concrete generic type:
```ts
class X extends ExtendedModel(modelClass>(SomeGenericClass), { ... }) { ... }
```
If you don't it will still compile, but the generic will be assumed to have `unknown` for all its generic parameters.
## Mixins
If you want a constrained mixin-style API for class models you can use `defineModelMixin` and `composeMixins`.
This avoids repeating `as unknown as ModelClass<...>` in each factory.
Pass the model properties as the first argument; an optional builder as the last argument adds methods.
Use `req()` as the second argument to declare that the base model must already expose a given shape before the mixin is applied.
```ts
@model("myApp/Entity")
class Entity extends Model({}) {}
// Props only – no builder needed
const countableMixin = defineModelMixin(
{ quantity: tProp(types.number, 0) }
)
// Props + methods via builder
const countableWithMethodsMixin = defineModelMixin(
{ quantity: tProp(types.number, 0) },
(Base) =>
class Countable extends Base {
incrementBy(delta: number) {
return this.quantity + delta
}
}
)
// Constrained mixin – requires `quantity` to already be on the base
const producerMixin = defineModelMixin(
{ produced: tProp(types.number, 0) },
req<{ quantity: number }>(),
(Base) =>
class Producer extends Base {
produceTotal() {
return this.produced + this.quantity
}
}
)
const ProductBase = composeMixins(Entity, countableWithMethodsMixin, producerMixin)
type Product = InstanceType
```
`ModelData` and `ModelCreationData` reflect the exact prop types from all composed mixins.
`composeMixins` enforces requirements at the type level: applying `producerMixin` before `countableWithMethodsMixin` is a TypeScript error.
When you need to derive a constraint from an already-composed base, extract the instance type:
```ts
const CountableBase = composeMixins(Entity, countableWithMethodsMixin)
type Countable = InstanceType
```
You can also call `composeMixins` **without a base class** when you want to bundle mixins for reuse without any shared base.
An implicit empty base is used, so you can apply the bundle to multiple concrete classes:
```ts
// Bundle mixins independently of any base
const ProductBundle = composeMixins(countableWithMethodsMixin, producerMixin)
@model("myApp/Product")
class Product extends ExtendedModel(ProductBundle, {}) {}
@model("myApp/Order")
class Order extends ExtendedModel(ProductBundle, {}) {}
```
You can also inline `composeMixins` directly into `ExtendedModel` when you don't need the composed base as a separate variable:
```ts
@model("myApp/Product")
class Product extends ExtendedModel(
composeMixins(Entity, countableWithMethodsMixin, producerMixin),
{ /* any additional own props */ }
) {}
```
## Snapshot pre/post-processors: `fromSnapshotProcessor` / `toSnapshotProcessor`
:::warning Processors must be pure
Snapshot processors must be **pure and deterministic**: they must not have
observable side effects, and the same input must always produce the same output.
They must also preserve the canonical snapshot round trip: passing the current
output snapshot through `fromSnapshotProcessor` must reproduce the same stored
model data. The library may skip the input processor when applying that already
current canonical snapshot. Do not use processors for logging, counters,
external-state reads, or other work that relies on every invocation being
observable.
This contract also applies to property snapshot processors, typed-property
processors, and codecs.
:::
`fromSnapshotProcessor` might be used to transform an input snapshot into the model's expected input snapshot.
This is useful, for example, for versioning.
Note that the `$modelType` property will always be there and will remain unchanged no matter the transformation.
```ts
// we split it here so it is accessible to `FromSnapshotDefaultType<>`
const modelProps = {
// in version 2 we split `fullName` into `firstName` and `lastName`
_version: prop(2),
firstName: prop(),
lastName: prop(),
}
@model("name")
class Name extends Model(modelProps, {
fromSnapshotProcessor(
sn: FromSnapshotDefaultType | { _version: 1; fullName: string }
) {
if (sn._version === 2) {
return sn
}
const [firstName, lastName] = sn.fullName.split(" ")
return {
_version: 2,
firstName,
lastName,
}
},
}) {
// ...
}
```
`toSnapshotProcessor` is the opposite and might be used to transform the model's expected output snapshot into another kind of object snapshot.
Note that the `$modelType` property will always be there and will remain unchanged no matter the transformation.
```ts
@model("name")
class Name extends Model(
{
firstName: prop(),
lastName: prop(),
},
{
toSnapshotProcessor(sn, modelInstance) {
// we want to also keep `fullName` for backwards compatibility
return {
...sn,
fullName: `${sn.firstName} ${sn.lastName}`,
}
},
}
) {
// ...
}
```
## Snapshot pre/post-processors for model properties
Model properties can have their own snapshot processors as well:
In this example we use snapshot processors to serialize a string array property as a comma-separated string.
```ts
class M extends Model({
names:
prop(() => [])
.withSnapshotProcessor({
fromSnapshot: (sn: string) => sn.split(","),
toSnapshot: (sn) => sn.join(","),
})
})
```
## Usage without decorators
Although this library was primarily intended to be used with decorators it is also possible to use it without them.
To do so you can use the `decoratedModel` function as shown below:
```ts
// note the `_` at the beginning of the name to distinguish it from the decorated version
class _Todo extends Model({
text: prop(),
done: prop(false),
}) {
// note how here we don't decorate the method directly, but on the next parameter instead
// @modelAction
setDone(done: boolean) {
this.done = done
}
// @modelAction
setText(text: string) {
this.text = text
}
// @computed
get fullText() {
return `${this.done ? "DONE" : "TODO"} - ${this.text}`
}
}
const Todo = decoratedModel(
// the string identifies this model type and must be unique across your whole application
// you may pass `undefined` if you don't want the model to be registered yet (e.g. for a base class)
"myCoolApp/Todo",
_Todo,
// here we pass what we would use as decorators to the class methods/properties above
// if we want to use multiple chained decorators we can pass an array of them instead
// note that any kind of TypeScript-compatible decorator is supported, not only the built-in ones!
{
setDone: modelAction,
setText: modelAction,
fullText: computed,
}
)
// needed to be able to do `SnapshotInOf`, type a variable as `Todo`, etc.
type Todo = _Todo
// if `_Todo` was generic then it would be `type Todo = _Todo`
const myTodo = new Todo({ done: false, text: "buy some milk" })
```
---
# dataModels
## Overview
Like class models, data models define behavior (actions/views) over observable data. Unlike class models, they keep the underlying data plain: snapshots do not gain a `$modelType` field. This tradeoff has a few consequences:
- The model instances are created lazily and when needed rather than eagerly.
- The only life-cycle hook, `onLazyInit`, runs the first time the wrapper for a data node is created. Reusing that wrapper preserves its instance fields and does not rerun the hook. If initialization throws, a later construction attempt retries initialization.
- Reconciliation is somewhat worse due to the lack of an ID property to uniquely identify the instances.
Data models are therefore a good fit for backend-shaped payloads that must remain free of library metadata while being edited locally and eventually sent back.
## Your first data model
Data models are defined much like [class models](./classModels.mdx), except that they extend `DataModel` instead of `Model`:
**prop**
```ts title="Todo.ts"
@model("myCoolApp/Todo")
export class Todo extends DataModel({
text: prop(), // required
done: prop(false), // defaults to `false`
}) {
@modelAction
setDone(done: boolean) {
this.done = done
}
@modelAction
setText(text: string) {
this.text = text
}
@computed
get asString() {
return `${!this.done ? "TODO" : "DONE"} ${this.text}`
}
}
```
**tProp**
```ts title="Todo.ts"
@model("myCoolApp/Todo")
export class Todo extends DataModel({
text: tProp(types.string), // required
done: tProp(types.boolean, false), // defaults to `false`
}) {
@modelAction
setDone(done: boolean) {
this.done = done
}
@modelAction
setText(text: string) {
this.text = text
}
@computed
get asString() {
return `${!this.done ? "TODO" : "DONE"} ${this.text}`
}
}
```
Properties are declared with `prop` / `tProp` in the same way as in class models; see [property declarations](./classModels.mdx#property-declarations).
:::note
Property defaults are applied only when wrapping a plain object with `new`, not when wrapping an existing tree node.
:::
## Data model rules
- Decorate the class with `@model` and give the model type a unique application-wide name.
- Extend `DataModel` with the properties that should be observable, snapshotable, and patchable.
- Access model data through either `this` or `this.$`.
- Change model data inside model actions.
:::warning No constructors
Do not declare a constructor in a data model. Use [`onLazyInit`](#life-cycle-event-hooks) when initialization logic is needed.
:::
Of course primitives are not the only kinds of data that a data model can hold. Arrays, plain objects, and other objects can be used as well.
:::warning Insert the data, not the model
Data models are wrappers around actual data object nodes. Creating an instance with `new` creates a wrapper over the data node (or over a new data node if the input was not one). That means the model itself can't be inserted into a tree; insert the wrapped data instead, which is available as `model.$`.
:::
## Creating a data model instance
An instance of the todo data node plus its wrapper model can be created like this:
```ts
const myTodo1 = new Todo({ done: true, text: "buy some milk" })
// `myTodo1.$` will hold the data object that can be inserted into a tree
```
Note that if the input data is a tree node then `myTodo1.$` will be exactly that same data tree node passed in the constructor.
If it is not a tree node then `myTodo1.$` will be the `toTreeNode` version of the passed data object.
Also, multiple calls to `new` over a same data tree node will return the same model instance every time.
In practice, you usually pass the data node around and create its wrapper with `new` only when you need the model's behavior.
Some examples:
```ts
const todoList: ModelData[] = [...];
// usually we would use `todoList[x]` to access the data ...
// until the moment we want to edit a particular todo
const editableTodo = new Todo(todoList[x]);
editableTodo.setText("hi there")
// once done we can just "throw away" the editable instance
```
```ts
const todoList: ModelData[] = [...];
const newTodo = new Todo({ done: false, text: "" })
// ...
newTodo.setText("buy milk")
// note how we insert into the tree the data, not the model itself!
todoList.push(newTodo.$);
```
## Automatic data model actions for property setters
Most times, the only action we need for a property is a setter. We can use the prop modifier `withSetter()` (`withSetter("assign")` has been deprecated) to reduce boilerplate and generate property setters. For example, the model above could be written as:
```ts
@model("myCoolApp/Todo")
export class Todo extends DataModel({
text: prop().withSetter(),
done: prop().withSetter(),
}) {}
const myTodo = new Todo({ text: "buy some coffee", done: false })
// this is now allowed and properly wrapped in two respective actions
myTodo.setText("buy some milk")
myTodo.setDone(true)
```
If you need to change data without declaring a custom `modelAction`, use the predefined `objectActions` or `arrayActions` helpers.
`withSetter` also accepts a value transform function. For example `withSetter(cloneTreeValue)` clones incoming non-primitive values before setting them, which is useful when the same object instance may be reused across different places in the tree. If you need clone options, wrap it (for example `withSetter((x) => cloneTreeValue(x, { generateNewIds: false }))`).
:::note
The transform function only runs in the generated setter (for example `model.setX(3)`). It does **not** run during model construction (`new Model({ x: 3 })`) or snapshot deserialization, where the value is assigned as provided.
:::
## Life-cycle event hooks
Data models only support a single limited life-cycle event hook:
- `onLazyInit()`, which is called the first time `new` is called to wrap a certain data node in the life-time of the application.
If you need something that runs more consistently consider using `onChildAttachedTo` over the data node parent itself.
## Runtime data
Runtime data that does not need to be snapshotted can be declared as a regular class property. Use MobX decorators when that runtime data also needs to be observable.
```ts
@model("myApp/SomeModel")
class SomeModel extends DataModel({
title: prop("demo"),
}) {
// non-observable runtime data
saveCount = 0
markSaved() {
this.saveCount++
}
// or observable in the usual MobX way
@observable
isSaving = false
@action
setSaving(isSaving: boolean) {
this.isSaving = isSaving
}
}
```
Note that this runtime data holds to the same lazy creation rules as the data model wrapper instance itself.
## Getting the TypeScript types for model data
- `ModelData` is the type of the model props without transformations (as accessible via `model.$`).
For example `ModelData` would return `{ text: string; done: boolean; }`.
## Flows (async actions)
While `@modelAction` defines sync model actions, async model actions are possible as well with the use of `@modelFlow`. A flow is a generator function where `yield* _await(x)` takes the place of `await x`:
**TypeScript**
```ts
interface Book {
title: string
price: number
}
@model("myApp/BookStore")
class BookStore extends DataModel({
books: prop(() => []),
}) {
@modelFlow
fetchMyBooksAsync = _async(function* (this: BookStore, token: string) {
const myBooks = yield* _await(myBackendClient.getBooks(token))
this.books = myBooks
})
}
```
In TypeScript, wrap the generator in `_async` and type `this` as the class, so the flow is typed as returning a promise.
**JavaScript**
```js
@model("myApp/BookStore")
class BookStore extends DataModel({
books: prop(() => []),
}) {
@modelFlow
*fetchMyBooksAsync(token) {
const myBooks = yield* _await(myBackendClient.getBooks(token))
this.books = myBooks
}
}
```
In either case it is called like any async function:
```ts
const myBookStore = new BookStore({})
await myBookStore.fetchMyBooksAsync("someToken")
```
:::warning `yield*`, not `yield`
Always use `yield* _await(...)`. `_await` only works when delegated to with `yield*`, and a plain `yield` does not work. Both `_async` and `_await` are imported from `mobx-keystone`.
:::
## Factory pattern / Generics
If you are _not_ relying on `tProp` to do runtime type checking it is possible to use this pattern to get generic classes:
```ts
@model("myApp/GenericPoint")
class GenericPoint extends DataModel(() => ({
x: prop(),
y: prop(),
})) {
@modelAction
setXY(x: T, y: T) {
this.x = x
this.y = y
}
}
@model("myApp/Generic3dPoint")
class Generic3dPoint extends ExtendedDataModel(() => ({
baseModel: modelClass>(GenericPoint),
props: {
z: prop(),
},
})) {
// ...
}
```
If you rely on `tProp` (and also `prop` really) a different possibility is to use a factory pattern with data models. For example:
```ts
function createModelClass(modelName: string, initialX: TX, initialY: TY) {
@model(`myApp/${modelName}`)
class MyModel extends DataModel({
x: prop(() => initialX),
y: prop(() => initialY),
}) {
@modelAction
setXY(x: TX, y: TY) {
this.x = x
this.y = y
}
}
return MyModel
}
const NumberMyModel = createModelClass("NumberMyModel", 10, 20)
type NumberMyModel = InstanceType
const numberMyModelInstance = new NumberMyModel({}) // this will be of type `NumberMyModel`
numberMyModelInstance.setXY(50, 60)
const StringMyModel = createModelClass("StringMyModel", "10", "20")
type StringMyModel = InstanceType
const stringMyModelInstance = new StringMyModel({}) // this will be of type `StringMyModel`
stringMyModelInstance.setXY("50", "60")
```
Note that the above will only work when not generating declaration maps. If you need to generate declarations (for example for a library) then it is a bit more tedious, but still possible:
```ts
export function createModelClass(modelName: string, initialX: TX, initialY: TY) {
const MyModelProps = DataModel({
x: prop(() => initialX),
y: prop(() => initialY),
})
@model(`myApp/${modelName}`)
class MyModel extends MyModelProps {
@modelAction
setXY(x: TX, y: TY) {
this.x = x
this.y = y
}
}
return MyModel as ModelClassDeclaration<
typeof MyModelProps,
{
setXY(x: TX, y: TY): void
}
>
}
```
## Inheritance
Model inheritance is possible with a few gotchas.
The first thing to bear in mind is that data models that extend from other data models must use `ExtendedDataModel` rather than the plain `DataModel`. For example:
```ts
@model("MyApp/Point")
class Point extends DataModel({
x: prop(),
y: prop(),
}) {
get sum() {
return this.x + this.y
}
}
// note how `ExtendedDataModel` is used
@model("MyApp/Point3d")
class Point3d extends ExtendedDataModel(Point, {
z: prop(),
}) {
get sum() {
return super.sum + this.z
}
}
```
Also, remember that if your base model has `onLazyInit` and you redeclare it in your extended model you will need to call `super.onLazyInit(...)` in the extended model.
When extending a generic class, use `modelClass` to specify the concrete generic type:
```ts
class X extends ExtendedDataModel(modelClass>(SomeGenericClass), { ... }) { ... }
```
If you don't it will still compile, but the generic will be assumed to have `unknown` for all its generic parameters.
## Usage without decorators
Although this library was primarily intended to be used with decorators it is also possible to use it without them.
To do so you can use the `decoratedModel` function as shown below:
```ts
// note the `_` at the beginning of the name to distinguish it from the decorated version
class _Todo extends DataModel({
text: prop(),
done: prop(),
}) {
// note how here we don't decorate the method directly, but on the next parameter instead
// @modelAction
setDone(done: boolean) {
this.done = done
}
// @modelAction
setText(text: string) {
this.text = text
}
// @computed
get fullText() {
return `${this.done ? "DONE" : "TODO"} - ${this.text}`
}
}
const Todo = decoratedModel(
// the string identifies this model type and must be unique across your whole application
// you may pass `undefined` if you don't want the model to be registered yet (e.g. for a base class)
"myCoolApp/Todo",
_Todo,
// here we pass what we would use as decorators to the class methods/properties above
// if we want to use multiple chained decorators we can pass an array of them instead
// note that any kind of TypeScript-compatible decorator is supported, not only the built-in ones!
{
setDone: modelAction,
setText: modelAction,
fullText: computed,
}
)
// needed to be able to do `SnapshotInOf`, type a variable as `Todo`, etc
type Todo = _Todo
// if `_Todo` was generic then it would be `type Todo = _Todo`
const myTodo = new Todo({ done: false, text: "buy some milk" })
```
---
# standardAndStandaloneActions
## Standalone Actions
Sometimes reusable state-changing logic does not belong to a particular model class but still needs action protection and middleware support. For example, an array-swap helper should be visible to [`undoMiddleware`](./actionMiddlewares/undoMiddleware.mdx). Define that logic as a standalone action:
```ts
const arraySwap = standaloneAction(
"myApp/arraySwap",
(array: T[], index1: number, index2: number): void => {
if (index2 < index1) {
;[index1, index2] = [index2, index1]
}
// since a same node cannot be in two places at once we will remove
// both then reinsert them
const [v1] = array.splice(index1, 1)
const [v2] = array.splice(index2 - 1, 1)
array.splice(index1, 0, v2)
array.splice(index2, 0, v1)
}
)
```
:::warning Standalone action requirements
- The name provided must be unique across your whole application.
- The first argument (the target) must always be an existing tree node.
:::
### `standaloneFlow`
If the same idea needs asynchronous steps, use `standaloneFlow`. It follows the same rules as `standaloneAction`, but behaves like a flow and returns a promise:
```ts
const renameAfterSave = standaloneFlow(
"myApp/renameAfterSave",
function* (todo: Todo, newText: string) {
// like model flows, use `yield* _await(X)` where you would use `await X`
yield* _await(api.saveTodo(todo.id, { text: newText }))
todo.setText(newText)
}
)
```
This is useful when you want middleware support for reusable async logic without attaching that logic to a specific model class.
## Standard Actions
Use the predefined `objectActions` and `arrayActions` to update objects and arrays without declaring custom actions. These helpers also work on class-model properties.
`objectActions` work over any kind of object (including models themselves) and offer:
- `set(obj, key, value)` to set a key.
- `delete(obj, key)` to delete a key.
- `assign(obj, partialObj)` to assign values (similar to `Object.assign`).
- `call(obj, methodName, ...args)` to call a method.
`arrayActions` work over arrays and offer:
- `set(array, index, value)` to set an index.
- `delete(array, index)` to delete an index.
- `setLength(array, length)` to set a new length.
- `swap(array, index1, index2)` to swap two array elements.
It also exposes the usual mutating array methods, including `pop`, `push`, `shift`, `unshift`, `splice`, `reverse`, and `sort`.
---
# treeLikeStructure
## Overview
`mobx-keystone`'s structure is based on a tree-like structure, where each node can be one of:
- A model instance.
- A plain object.
- An array.
- A primitive value (`string`, `boolean`, `number`, `null`, `undefined`).
By default, arrays _cannot_ hold `undefined` values, but they _can_ hold `null` values. This rule exists for JSON compatibility. If you really need arrays with `undefined` values, you can enable them in the global configuration:
```ts
setGlobalConfig({
allowUndefinedArrayElements: true,
})
```
Since the structure is a tree, this means these tree rules apply:
1. A non-primitive (object) node can have zero or one parent.
2. A non-primitive (object) node can have zero to infinite children.
3. From rules 1 and 2 we can extract that the same non-primitive node can only be in a single tree and only once.
4. Primitive nodes are always copied by value, so none of the rules above apply.
5. Note that class models with the `valueType: true` option will get cloned automatically before getting inserted as a child of another node so, for all practical purposes, rule 3 does not apply and acts more akin to a primitive.
As an example of rule 1, this would not be allowed:
```ts
// given `someModel`, `someOtherModel`, `someArray`
// ok, `someArray` has now one parent and becomes a tree node object
someModel.setArray(someArray)
// but this would throw since `someArray` is already a tree node object which already has one parent
someOtherModel.setArray(someArray)
```
But as rule 4 states, this would be ok:
```ts
// given `someModel`, `someOtherModel`
const somePrimitive = "hi!"
// ok, the primitive is copied, and has now one parent
someModel.setPrimitive(somePrimitive)
// ok too, since the primitive is copied again, and has one parent
someOtherModel.setPrimitive(somePrimitive)
```
A way to work around rule 1 is possible thanks to the use of references as shown in the [references](./references.mdx) section.
### Working with large arrays
Inserting or removing array elements updates the parent paths of the following tree nodes, so inserting near the beginning of a large array costs more than appending to it.
Group related edits in one `modelAction` so MobX reactions and snapshot listeners can process the completed edit together.
## How objects are transformed into nodes
A model/object/array is turned into a tree node under the following circumstances:
- Model instances are _always_ tree nodes.
- Plain objects / arrays are turned into tree nodes as soon as they become children of another tree node.
To check if a non-primitive has been turned into a tree node you can use `isTreeNode(value: object): boolean`, or
`assertIsTreeNode(value: object, argName: string = "argument"): asserts value is object` to assert it.
To turn a non-primitive into a tree node you can use `toTreeNode(value: T): T`. If the object is already a tree node then the same object will be returned.
Additionally, `toTreeNode(type: TType, value: V): V` can be used with a type checker which will be invoked to check the data (when auto model type checking is enabled) if desired.
## Traversal methods
When a non-primitive value is turned into a tree node it gains access to certain methods that allow traversing the data tree:
### `getParentPath`
```ts
getParentPath(value: object): ParentPath | undefined
```
Returns the parent of the target plus the path from the parent to the target, or `undefined` if it has no parent.
### `getParent`
```ts
getParent(value: object): T | undefined
```
Returns the parent object of the target object, or `undefined` if there's no parent.
### `getParentToChildPath`
```ts
getParentToChildPath(fromParent: object, toChild: object): Path | undefined
```
Gets the path to get from a parent to a given child.
Returns an empty array if the child is actually the given parent or `undefined` if the child is not a child of the parent.
### `isModelDataObject`
```ts
isModelDataObject(value: object): boolean
```
Returns `true` if a given object is a model interim data object (`$`).
### `getRootPath`
```ts
getRootPath(value: object): RootPath
```
Returns the root of the target, the path from the root to get to the target and the list of objects from root (included) until target (included).
### `getRoot`
```ts
getRoot(value: object): T
```
Returns the root of the target object, or itself if the target is a root.
:::warning Detached nodes
If a node gets detached from its parent tree, `getRoot(node)` will return that same node.
This matters in reactive code (`computed`, `autorun`, etc.). If a computed uses `getRoot(this)` and then reads a property that resolves back to the same computed, MobX will throw a cycle error.
When you need to access an actual registered root store, prefer `getRootStore` and guard for `undefined`:
```ts
const rootStore = getRootStore(this)
if (!rootStore) {
return undefined
}
return rootStore.someValue
```
:::
### `isRoot`
```ts
isRoot(value: object): boolean
```
Returns `true` if a given object is a root object.
### `isChildOfParent`
```ts
isChildOfParent(child: object, parent: object): boolean
```
Returns `true` if the target is a "child" of the tree of the given "parent" object.
### `isParentOfChild`
```ts
isParentOfChild(parent: object, child: object): boolean
```
Returns `true` if the target is a "parent" that has in its tree the given "child" object.
### `resolvePath`
```ts
resolvePath(pathRootObject: object, path: Path): { resolved: true; value: T } | { resolved: false }
```
Resolves a path from an object, returning an object with `{ resolved: true, value: T }` or `{ resolved: false }`.
### `findParent`
```ts
findParent(child: object, predicate: (parent: object) => boolean, maxDepth = 0): T | undefined
```
Iterates through all the parents (from the nearest until the root) until one of them matches the given predicate.
If the predicate is matched it will return the found node.
If none is found it will return `undefined`.
A max depth of 0 is infinite, but another one can be given.
### `findParentPath`
```ts
findParentPath(child: object, predicate: (parent: object) => boolean, maxDepth = 0): FoundParentPath | undefined
```
Iterates through all the parents (from the nearest until the root) until one of them matches the given predicate.
If the predicate is matched it will return the found node and the path from the parent to the child.
If none is found it will return `undefined`.
A max depth of 0 is infinite, but another one can be given.
### `findChildren`
```ts
findChildren(root: object, predicate: (node: object) => boolean, options?: { deep?: boolean }): ReadonlySet
```
Iterates through all children and collects them in a set if the given predicate matches.
Pass the options object with the `deep` option (defaults to `false`) set to `true` to get the children deeply or `false` to get them shallowly.
### `getChildrenObjects`
```ts
getChildrenObjects(node: object, options?: { deep?: boolean }): ReadonlySet