mobx-state-tree

  • Version 5.0.3
  • Published
  • 1.25 MB
  • No dependencies
  • MIT license

Install

npm i mobx-state-tree
yarn add mobx-state-tree
pnpm add mobx-state-tree

Overview

Opinionated, transactional, MobX powered state container

Index

Variables

Functions

Interfaces

Type Aliases

Variables

variable types

const types: {
enumeration: typeof enumeration;
model: typeof model;
compose: typeof compose;
custom: typeof custom;
reference: typeof reference;
safeReference: typeof safeReference;
union: typeof union;
optional: typeof optional;
literal: typeof literal;
maybe: typeof maybe;
maybeNull: typeof maybeNull;
refinement: typeof refinement;
string: import('../internal').ISimpleType<string>;
boolean: import('../internal').ISimpleType<boolean>;
number: import('../internal').ISimpleType<number>;
integer: import('../internal').ISimpleType<number>;
Date: import('../internal').IType<number | Date, number, Date>;
map: typeof map;
array: typeof array;
frozen: typeof frozen;
identifier: import('../internal').ISimpleType<string>;
identifierNumber: import('../internal').ISimpleType<number>;
late: typeof late;
undefined: import('../internal').ISimpleType<undefined>;
null: import('../internal').ISimpleType<null>;
snapshotProcessor: typeof snapshotProcessor;
};

    Functions

    function addDisposer

    addDisposer: (target: IAnyStateTreeNode, disposer: IDisposer) => IDisposer;
    • Use this utility to register a function that should be called whenever the targeted state tree node is destroyed. This is a useful alternative to managing cleanup methods yourself using the beforeDestroy hook.

      This methods returns the same disposer that was passed as argument.

      Example:

      const Todo = types.model({
      title: types.string
      }).actions(self => ({
      afterCreate() {
      const autoSaveDisposer = reaction(
      () => getSnapshot(self),
      snapshot => sendSnapshotToServerSomehow(snapshot)
      )
      // stop sending updates to server if this
      // instance is destroyed
      addDisposer(self, autoSaveDisposer)
      }
      }))

      Parameter target

      Parameter disposer

      Returns

      The same disposer that was passed as argument

    function addMiddleware

    addMiddleware: (
    target: IAnyStateTreeNode,
    handler: IMiddlewareHandler,
    includeHooks?: boolean
    ) => IDisposer;
    • Middleware can be used to intercept any action is invoked on the subtree where it is attached. If a tree is protected (by default), this means that any mutation of the tree will pass through your middleware.

      For more details, see the [middleware docs](concepts/middleware.md)

      Parameter target

      Node to apply the middleware to.

      Parameter middleware

      Middleware to apply.

      Returns

      A callable function to dispose the middleware.

    function applyAction

    applyAction: (
    target: IAnyStateTreeNode,
    actions: ISerializedActionCall | ISerializedActionCall[]
    ) => void;
    • Applies an action or a series of actions in a single MobX transaction. Does not return any value Takes an action description as produced by the onAction middleware.

      Parameter target

      Parameter actions

    function applyPatch

    applyPatch: (
    target: IAnyStateTreeNode,
    patch: IJsonPatch | ReadonlyArray<IJsonPatch>
    ) => void;
    • Applies a JSON-patch to the given model instance or bails out if the patch couldn't be applied See [patches](https://github.com/mobxjs/mobx-state-tree#patches) for more details.

      Can apply a single past, or an array of patches.

      Parameter target

      Parameter patch

      Returns

    function applySnapshot

    applySnapshot: <C>(
    target: IStateTreeNode<IType<C, any, any>>,
    snapshot: C
    ) => void;
    • Applies a snapshot to a given model instances. Patch and snapshot listeners will be invoked as usual.

      Parameter target

      Parameter snapshot

      Returns

    function cast

    cast: {
    <O extends string | number | boolean = never>(snapshotOrInstance: O): O;
    <O = never>(
    snapshotOrInstance:
    | TypeOfValue<O>['CreationType']
    | TypeOfValue<O>['SnapshotType']
    | TypeOfValue<O>['Type']
    ): O;
    };

      function castFlowReturn

      castFlowReturn: <T>(val: T) => T;
      • Parameter val

        Returns

        Deprecated

        Not needed since TS3.6. Used for TypeScript to make flows that return a promise return the actual promise result.

      function castToReferenceSnapshot

      castToReferenceSnapshot: <I>(
      instance: I
      ) => Extract<I, IAnyStateTreeNode> extends never ? I : ReferenceIdentifier;
      • Casts a node instance type to a reference snapshot type so it can be assigned to a refernence snapshot (e.g. to be used inside a create call). Note that this is just a cast for the type system, this is, it won't actually convert an instance to a refererence snapshot, but just fool typescript into thinking so.

        Example:

        const ModelA = types.model({
        id: types.identifier,
        n: types.number
        }).actions(self => ({
        setN(aNumber: number) {
        self.n = aNumber
        }
        }))
        const ModelB = types.model({
        refA: types.reference(ModelA)
        })
        const a = ModelA.create({ id: 'someId', n: 5 });
        // this will allow the compiler to use a model as if it were a reference snapshot
        const b = ModelB.create({ refA: castToReferenceSnapshot(a)})

        Parameter instance

        Instance

        Returns

        The same object casted as an reference snapshot (string or number)

      function castToSnapshot

      castToSnapshot: <I>(
      snapshotOrInstance: I
      ) => Extract<I, IAnyStateTreeNode> extends never
      ? I
      : TypeOfValue<I>['CreationType'];
      • Casts a node instance type to an snapshot type so it can be assigned to a type snapshot (e.g. to be used inside a create call). Note that this is just a cast for the type system, this is, it won't actually convert an instance to a snapshot, but just fool typescript into thinking so.

        Example:

        const ModelA = types.model({
        n: types.number
        }).actions(self => ({
        setN(aNumber: number) {
        self.n = aNumber
        }
        }))
        const ModelB = types.model({
        innerModel: ModelA
        })
        const a = ModelA.create({ n: 5 });
        // this will allow the compiler to use a model as if it were a snapshot
        const b = ModelB.create({ innerModel: castToSnapshot(a)})

        Parameter snapshotOrInstance

        Snapshot or instance

        Returns

        The same object casted as an input (creation) snapshot

      function clone

      clone: <T extends IAnyStateTreeNode>(
      source: T,
      keepEnvironment?: boolean | any
      ) => T;
      • Returns a deep copy of the given state tree node as new tree. Short hand for snapshot(x) = getType(x).create(getSnapshot(x))

        _Tip: clone will create a literal copy, including the same identifiers. To modify identifiers etc during cloning, don't use clone but take a snapshot of the tree, modify it, and create new instance_

        Parameter source

        Parameter keepEnvironment

        indicates whether the clone should inherit the same environment (true, the default), or not have an environment (false). If an object is passed in as second argument, that will act as the environment for the cloned tree.

        Returns

      function createActionTrackingMiddleware

      createActionTrackingMiddleware: <T = any>(
      hooks: IActionTrackingMiddlewareHooks<T>
      ) => IMiddlewareHandler;
      • Note: Consider migrating to createActionTrackingMiddleware2, it is easier to use.

        Convenience utility to create action based middleware that supports async processes more easily. All hooks are called for both synchronous and asynchronous actions. Except that either onSuccess or onFail is called

        The create middleware tracks the process of an action (assuming it passes the filter). onResume can return any value, which will be passed as second argument to any other hook. This makes it possible to keep state during a process.

        See the atomic middleware for an example

        Parameter hooks

        Returns

      function createActionTrackingMiddleware2

      createActionTrackingMiddleware2: <TEnv = any>(
      middlewareHooks: IActionTrackingMiddleware2Hooks<TEnv>
      ) => IMiddlewareHandler;
      • Convenience utility to create action based middleware that supports async processes more easily. The flow is like this: - for each action: if filter passes -> onStart -> (inner actions recursively) -> onFinish

        Example: if we had an action a that called inside an action b1, then b2 the flow would be: - filter(a) - onStart(a) - filter(b1) - onStart(b1) - onFinish(b1) - filter(b2) - onStart(b2) - onFinish(b2) - onFinish(a)

        The flow is the same no matter if the actions are sync or async.

        See the atomic middleware for an example

        Parameter hooks

        Returns

      function decorate

      decorate: <T extends Function>(
      handler: IMiddlewareHandler,
      fn: T,
      includeHooks?: boolean
      ) => T;
      • Binds middleware to a specific action.

        Example:

        type.actions(self => {
        function takeA____() {
        self.toilet.donate()
        self.wipe()
        self.wipe()
        self.toilet.flush()
        }
        return {
        takeA____: decorate(atomic, takeA____)
        }
        })

        Parameter handler

        Parameter fn

        Parameter includeHooks

        Returns

        The original function

      function destroy

      destroy: (target: IAnyStateTreeNode) => void;
      • Removes a model element from the state tree, and mark it as end-of-life; the element should not be used anymore

      function detach

      detach: <T extends IAnyStateTreeNode>(target: T) => T;
      • Removes a model element from the state tree, and let it live on as a new state tree

      function escapeJsonPath

      escapeJsonPath: (path: string) => string;
      • Escape slashes and backslashes.

        http://tools.ietf.org/html/rfc6901

      function flow

      flow: <R, Args extends any[]>(
      generator: (...args: Args) => Generator<Promise<any>, R, any>
      ) => (...args: Args) => Promise<FlowReturn<R>>;
      • See [asynchronous actions](concepts/async-actions.md).

        Returns

        The flow as a promise.

      function getChildType

      getChildType: (object: IAnyStateTreeNode, propertyName?: string) => IAnyType;
      • Returns the _declared_ type of the given sub property of an object, array or map. In the case of arrays and maps the property name is optional and will be ignored.

        Example:

        const Box = types.model({ x: 0, y: 0 })
        const box = Box.create()
        console.log(getChildType(box, "x").name) // 'number'

        Parameter object

        Parameter propertyName

        Returns

      function getEnv

      getEnv: <T = any>(target: IAnyStateTreeNode) => T;
      • Returns the environment of the current state tree. For more info on environments, see [Dependency injection](https://github.com/mobxjs/mobx-state-tree#dependency-injection)

        Please note that in child nodes access to the root is only possible once the afterAttach hook has fired

        Returns an empty environment if the tree wasn't initialized with an environment

        Parameter target

        Returns

      function getIdentifier

      getIdentifier: (target: IAnyStateTreeNode) => string | null;
      • Returns the identifier of the target node. This is the *string normalized* identifier, which might not match the type of the identifier attribute

        Parameter target

        Returns

      function getLivelinessChecking

      getLivelinessChecking: () => LivelinessMode;
      • Returns the current liveliness checking mode.

        Returns

        "warn", "error" or "ignore"

      function getMembers

      getMembers: (target: IAnyStateTreeNode) => IModelReflectionData;
      • Returns a reflection of the model node, including name, properties, views, volatile and actions.

        Parameter target

        Returns

      function getNodeId

      getNodeId: (target: IAnyStateTreeNode) => number;
      • Returns the unique node id (not to be confused with the instance identifier) for a given instance. This id is a number that is unique for each instance.

        Parameter target

        Returns

      function getParent

      getParent: <IT extends IAnyStateTreeNode | IAnyComplexType>(
      target: IAnyStateTreeNode,
      depth?: number
      ) => TypeOrStateTreeNodeToStateTreeNode<IT>;
      • Returns the immediate parent of this object, or throws.

        Note that the immediate parent can be either an object, map or array, and doesn't necessarily refer to the parent model.

        Please note that in child nodes access to the root is only possible once the afterAttach hook has fired.

        Parameter target

        Parameter depth

        How far should we look upward? 1 by default.

        Returns

      function getParentOfType

      getParentOfType: <IT extends IAnyComplexType>(
      target: IAnyStateTreeNode,
      type: IT
      ) => IT['Type'];
      • Returns the target's parent of a given type, or throws.

        Parameter target

        Parameter type

        Returns

      function getPath

      getPath: (target: IAnyStateTreeNode) => string;
      • Returns the path of the given object in the model tree

        Parameter target

        Returns

      function getPathParts

      getPathParts: (target: IAnyStateTreeNode) => string[];
      • Returns the path of the given object as unescaped string array.

        Parameter target

        Returns

      function getPropertyMembers

      getPropertyMembers: (
      typeOrNode: IAnyModelType | IAnyStateTreeNode
      ) => IModelReflectionPropertiesData;
      • Returns a reflection of the model type properties and name for either a model type or model node.

        Parameter typeOrNode

        Returns

      function getRelativePath

      getRelativePath: (base: IAnyStateTreeNode, target: IAnyStateTreeNode) => string;
      • Given two state tree nodes that are part of the same tree, returns the shortest jsonpath needed to navigate from the one to the other

        Parameter base

        Parameter target

        Returns

      function getRoot

      getRoot: <IT extends IAnyStateTreeNode | IAnyComplexType>(
      target: IAnyStateTreeNode
      ) => TypeOrStateTreeNodeToStateTreeNode<IT>;
      • Given an object in a model tree, returns the root object of that tree.

        Please note that in child nodes access to the root is only possible once the afterAttach hook has fired.

        Parameter target

        Returns

      function getRunningActionContext

      getRunningActionContext: () => IActionContext | undefined;
      • Returns the currently executing MST action context, or undefined if none.

      function getSnapshot

      getSnapshot: <S>(
      target: IStateTreeNode<IType<any, S, any>>,
      applyPostProcess?: boolean
      ) => S;
      • Calculates a snapshot from the given model instance. The snapshot will always reflect the latest state but use structural sharing where possible. Doesn't require MobX transactions to be completed.

        Parameter target

        Parameter applyPostProcess

        If true (the default) then postProcessSnapshot gets applied.

        Returns

      function getType

      getType: (object: IAnyStateTreeNode) => IAnyComplexType;
      • Returns the _actual_ type of the given tree node. (Or throws)

        Parameter object

        Returns

      function hasParent

      hasParent: (target: IAnyStateTreeNode, depth?: number) => boolean;
      • Given a model instance, returns true if the object has a parent, that is, is part of another object, map or array.

        Parameter target

        Parameter depth

        How far should we look upward? 1 by default.

        Returns

      function hasParentOfType

      hasParentOfType: (target: IAnyStateTreeNode, type: IAnyComplexType) => boolean;
      • Given a model instance, returns true if the object has a parent of given type, that is, is part of another object, map or array

        Parameter target

        Parameter type

        Returns

      function isActionContextChildOf

      isActionContextChildOf: (
      actionContext: IActionContext,
      parent: number | IActionContext | IMiddlewareEvent
      ) => boolean;
      • Returns if the given action context is a parent of this action context.

      function isActionContextThisOrChildOf

      isActionContextThisOrChildOf: (
      actionContext: IActionContext,
      parentOrThis: number | IActionContext | IMiddlewareEvent
      ) => boolean;
      • Returns if the given action context is this or a parent of this action context.

      function isAlive

      isAlive: (target: IAnyStateTreeNode) => boolean;
      • Returns true if the given state tree node is not killed yet. This means that the node is still a part of a tree, and that destroy has not been called. If a node is not alive anymore, the only thing one can do with it is requesting it's last path and snapshot

        Parameter target

        Returns

      function isArrayType

      isArrayType: <Items extends IAnyType = IAnyType>(
      type: IAnyType
      ) => type is IArrayType<Items>;
      • Returns if a given value represents an array type.

        Parameter type

        Returns

        true if the type is an array type.

      function isFrozenType

      isFrozenType: <IT extends IType<any, T, T>, T = any>(type: IT) => type is IT;
      • Returns if a given value represents a frozen type.

        Parameter type

        Returns

      function isIdentifierType

      isIdentifierType: <IT extends ISimpleType<string> | ISimpleType<number>>(
      type: IT
      ) => type is IT;
      • Returns if a given value represents an identifier type.

        Parameter type

        Returns

      function isLateType

      isLateType: <IT extends IAnyType>(type: IT) => type is IT;
      • Returns if a given value represents a late type.

        Parameter type

        Returns

      function isLiteralType

      isLiteralType: <IT extends ISimpleType<any>>(type: IT) => type is IT;
      • Returns if a given value represents a literal type.

        Parameter type

        Returns

      function isMapType

      isMapType: <Items extends IAnyType = IAnyType>(
      type: IAnyType
      ) => type is IMapType<Items>;
      • Returns if a given value represents a map type.

        Parameter type

        Returns

        true if it is a map type.

      function isModelType

      isModelType: <IT extends IAnyModelType = IAnyModelType>(
      type: IAnyType
      ) => type is IT;
      • Returns if a given value represents a model type.

        Parameter type

        Returns

      function isOptionalType

      isOptionalType: <IT extends IAnyType>(type: IT) => type is IT;
      • Returns if a value represents an optional type.

        IT

        Parameter type

        Returns

      function isPrimitiveType

      isPrimitiveType: <
      IT extends
      | ISimpleType<string>
      | ISimpleType<number>
      | ISimpleType<boolean>
      | IType<number | Date, number, Date>
      >(
      type: IT
      ) => type is IT;
      • Returns if a given value represents a primitive type.

        Parameter type

        Returns

      function isProtected

      isProtected: (target: IAnyStateTreeNode) => boolean;
      • Returns true if the object is in protected mode,

        See Also

        • protect

      function isReferenceType

      isReferenceType: <IT extends IReferenceType<any>>(type: IT) => type is IT;
      • Returns if a given value represents a reference type.

        Parameter type

        Returns

      function isRefinementType

      isRefinementType: <IT extends IAnyType>(type: IT) => type is IT;
      • Returns if a given value is a refinement type.

        Parameter type

        Returns

      function isRoot

      isRoot: (target: IAnyStateTreeNode) => boolean;
      • Returns true if the given object is the root of a model tree.

        Parameter target

        Returns

      function isStateTreeNode

      isStateTreeNode: <IT extends IAnyComplexType = IAnyComplexType>(
      value: any
      ) => value is STNValue<Instance<IT>, IT>;
      • Returns true if the given value is a node in a state tree. More precisely, that is, if the value is an instance of a types.model, types.array or types.map.

        Parameter value

        Returns

        true if the value is a state tree node.

      function isType

      isType: (value: any) => value is IAnyType;
      • Returns if a given value represents a type.

        Parameter value

        Value to check.

        Returns

        true if the value is a type.

      function isUnionType

      isUnionType: <IT extends IAnyType>(type: IT) => type is IT;
      • Returns if a given value represents a union type.

        Parameter type

        Returns

      function isValidReference

      isValidReference: <N extends IAnyStateTreeNode>(
      getter: () => N | null | undefined,
      checkIfAlive?: boolean
      ) => boolean;
      • Tests if a reference is valid (pointing to an existing node and optionally if alive) and returns if the check passes or not.

        Parameter getter

        Function to access the reference.

        Parameter checkIfAlive

        true to also make sure the referenced node is alive (default), false to skip this check.

        Returns

      function joinJsonPath

      joinJsonPath: (path: string[]) => string;
      • Generates a json-path compliant json path from path parts.

        Parameter path

        Returns

      function onAction

      onAction: (
      target: IAnyStateTreeNode,
      listener: (call: ISerializedActionCall) => void,
      attachAfter?: boolean
      ) => IDisposer;
      • Registers a function that will be invoked for each action that is called on the provided model instance, or to any of its children. See [actions](https://github.com/mobxjs/mobx-state-tree#actions) for more details. onAction events are emitted only for the outermost called action in the stack. Action can also be intercepted by middleware using addMiddleware to change the function call before it will be run.

        Not all action arguments might be serializable. For unserializable arguments, a struct like { $MST_UNSERIALIZABLE: true, type: "someType" } will be generated. MST Nodes are considered non-serializable as well (they could be serialized as there snapshot, but it is uncertain whether an replaying party will be able to handle such a non-instantiated snapshot). Rather, when using onAction middleware, one should consider in passing arguments which are 1: an id, 2: a (relative) path, or 3: a snapshot. Instead of a real MST node.

        Example:

        const Todo = types.model({
        task: types.string
        })
        const TodoStore = types.model({
        todos: types.array(Todo)
        }).actions(self => ({
        add(todo) {
        self.todos.push(todo);
        }
        }))
        const s = TodoStore.create({ todos: [] })
        let disposer = onAction(s, (call) => {
        console.log(call);
        })
        s.add({ task: "Grab a coffee" })
        // Logs: { name: "add", path: "", args: [{ task: "Grab a coffee" }] }

        Parameter target

        Parameter listener

        Parameter attachAfter

        (default false) fires the listener *after* the action has executed instead of before.

        Returns

      function onPatch

      onPatch: (
      target: IAnyStateTreeNode,
      callback: (patch: IJsonPatch, reversePatch: IJsonPatch) => void
      ) => IDisposer;
      • Registers a function that will be invoked for each mutation that is applied to the provided model instance, or to any of its children. See [patches](https://github.com/mobxjs/mobx-state-tree#patches) for more details. onPatch events are emitted immediately and will not await the end of a transaction. Patches can be used to deep observe a model tree.

        Parameter target

        the model instance from which to receive patches

        Parameter callback

        the callback that is invoked for each patch. The reversePatch is a patch that would actually undo the emitted patch

        Returns

        function to remove the listener

      function onSnapshot

      onSnapshot: <S>(
      target: IStateTreeNode<IType<any, S, any>>,
      callback: (snapshot: S) => void
      ) => IDisposer;
      • Registers a function that is invoked whenever a new snapshot for the given model instance is available. The listener will only be fire at the end of the current MobX (trans)action. See [snapshots](https://github.com/mobxjs/mobx-state-tree#snapshots) for more details.

        Parameter target

        Parameter callback

        Returns

      function process

      process: {
      <R>(generator: () => IterableIterator<any>): () => Promise<R>;
      <A1>(generator: (a1: A1) => IterableIterator<any>): (a1: A1) => Promise<any>;
      <A1, A2>(generator: (a1: A1, a2: A2) => IterableIterator<any>): (
      a1: A1,
      a2: A2
      ) => Promise<any>;
      <A1, A2, A3>(generator: (a1: A1, a2: A2, a3: A3) => IterableIterator<any>): (
      a1: A1,
      a2: A2,
      a3: A3
      ) => Promise<any>;
      <A1, A2, A3, A4>(
      generator: (a1: A1, a2: A2, a3: A3, a4: A4) => IterableIterator<any>
      ): (a1: A1, a2: A2, a3: A3, a4: A4) => Promise<any>;
      <A1, A2, A3, A4, A5>(
      generator: (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5) => IterableIterator<any>
      ): (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5) => Promise<any>;
      <A1, A2, A3, A4, A5, A6>(
      generator: (
      a1: A1,
      a2: A2,
      a3: A3,
      a4: A4,
      a5: A5,
      a6: A6
      ) => IterableIterator<any>
      ): (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6) => Promise<any>;
      <A1, A2, A3, A4, A5, A6, A7>(
      generator: (
      a1: A1,
      a2: A2,
      a3: A3,
      a4: A4,
      a5: A5,
      a6: A6,
      a7: A7
      ) => IterableIterator<any>
      ): (a1: A1, a2: A2, a3: A3, a4: A4, a5: A5, a6: A6, a7: A7) => Promise<any>;
      <A1, A2, A3, A4, A5, A6, A7, A8>(
      generator: (
      a1: A1,
      a2: A2,
      a3: A3,
      a4: A4,
      a5: A5,
      a6: A6,
      a7: A7,
      a8: A8
      ) => IterableIterator<any>
      ): (
      a1: A1,
      a2: A2,
      a3: A3,
      a4: A4,
      a5: A5,
      a6: A6,
      a7: A7,
      a8: A8
      ) => Promise<any>;
      };
      • Deprecated

        has been renamed to flow().

      function protect

      protect: (target: IAnyStateTreeNode) => void;
      • The inverse of unprotect.

        Parameter target

      function recordActions

      recordActions: (
      subject: IAnyStateTreeNode,
      filter?: (
      action: ISerializedActionCall,
      actionContext: IActionContext | undefined
      ) => boolean
      ) => IActionRecorder;
      • Small abstraction around onAction and applyAction, attaches an action listener to a tree and records all the actions emitted. Returns an recorder object with the following signature:

        Example:

        export interface IActionRecorder {
        // the recorded actions
        actions: ISerializedActionCall[]
        // true if currently recording
        recording: boolean
        // stop recording actions
        stop(): void
        // resume recording actions
        resume(): void
        // apply all the recorded actions on the given object
        replay(target: IAnyStateTreeNode): void
        }

        The optional filter function allows to skip recording certain actions.

        Parameter subject

        Returns

      function recordPatches

      recordPatches: (
      subject: IAnyStateTreeNode,
      filter?: (
      patch: IJsonPatch,
      inversePatch: IJsonPatch,
      actionContext: IActionContext | undefined
      ) => boolean
      ) => IPatchRecorder;
      • Small abstraction around onPatch and applyPatch, attaches a patch listener to a tree and records all the patches. Returns an recorder object with the following signature:

        Example:

        export interface IPatchRecorder {
        // the recorded patches
        patches: IJsonPatch[]
        // the inverse of the recorded patches
        inversePatches: IJsonPatch[]
        // true if currently recording
        recording: boolean
        // stop recording patches
        stop(): void
        // resume recording patches
        resume(): void
        // apply all the recorded patches on the given target (the original subject if omitted)
        replay(target?: IAnyStateTreeNode): void
        // reverse apply the recorded patches on the given target (the original subject if omitted)
        // stops the recorder if not already stopped
        undo(): void
        }

        The optional filter function allows to skip recording certain patches.

        Parameter subject

        Parameter filter

        Returns

      function resolveIdentifier

      resolveIdentifier: <IT extends IAnyModelType>(
      type: IT,
      target: IAnyStateTreeNode,
      identifier: ReferenceIdentifier
      ) => IT['Type'] | undefined;
      • Resolves a model instance given a root target, the type and the identifier you are searching for. Returns undefined if no value can be found.

        Parameter type

        Parameter target

        Parameter identifier

        Returns

      function resolvePath

      resolvePath: (target: IAnyStateTreeNode, path: string) => any;
      • Resolves a path relatively to a given object. Returns undefined if no value can be found.

        Parameter target

        Parameter path

        escaped json path

        Returns

      function setLivelinessChecking

      setLivelinessChecking: (mode: LivelinessMode) => void;
      • Defines what MST should do when running into reads / writes to objects that have died. By default it will print a warning. Use the "error" option to easy debugging to see where the error was thrown and when the offending read / write took place

        Parameter mode

        "warn", "error" or "ignore"

      function setLivelynessChecking

      setLivelynessChecking: (mode: LivelinessMode) => void;
      • Parameter mode

        "warn", "error" or "ignore"

        Deprecated

        use setLivelinessChecking instead

        Defines what MST should do when running into reads / writes to objects that have died. By default it will print a warning. Use the "error" option to easy debugging to see where the error was thrown and when the offending read / write took place

      function splitJsonPath

      splitJsonPath: (path: string) => string[];
      • Splits and decodes a json path into several parts.

        Parameter path

        Returns

      function toGenerator

      toGenerator: <R>(p: Promise<R>) => Generator<Promise<R>, R, R>;
      • experimental api - might change on minor/patch releases

        Convert a promise to a generator yielding that promise This is intended to allow for usage of yield* in async actions to retain the promise return type.

        Example:

        function getDataAsync(input: string): Promise<number> { ... }
        const someModel.actions(self => ({
        someAction: flow(function*() {
        // value is typed as number
        const value = yield* toGenerator(getDataAsync("input value"));
        ...
        })
        }))

        Modifiers

        • @experimental

      function toGeneratorFunction

      toGeneratorFunction: <R, Args extends any[]>(
      p: (...args: Args) => Promise<R>
      ) => (...args: Args) => Generator<Promise<R>, R, R>;
      • experimental api - might change on minor/patch releases

        Convert a promise-returning function to a generator-returning one. This is intended to allow for usage of yield* in async actions to retain the promise return type.

        Example:

        function getDataAsync(input: string): Promise<number> { ... }
        const getDataGen = toGeneratorFunction(getDataAsync);
        const someModel.actions(self => ({
        someAction: flow(function*() {
        // value is typed as number
        const value = yield* getDataGen("input value");
        ...
        })
        }))

        Modifiers

        • @experimental

      function tryReference

      tryReference: <N extends IAnyStateTreeNode>(
      getter: () => N | null | undefined,
      checkIfAlive?: boolean
      ) => N | undefined;
      • Tests if a reference is valid (pointing to an existing node and optionally if alive) and returns such reference if it the check passes, else it returns undefined.

        Parameter getter

        Function to access the reference.

        Parameter checkIfAlive

        true to also make sure the referenced node is alive (default), false to skip this check.

        Returns

      function tryResolve

      tryResolve: (target: IAnyStateTreeNode, path: string) => any;
      • Try to resolve a given path relative to a given node.

        Parameter target

        Parameter path

        Returns

      function typecheck

      typecheck: <IT extends IAnyType>(type: IT, value: ExtractCSTWithSTN<IT>) => void;
      • Run's the typechecker for the given type on the given value, which can be a snapshot or an instance. Throws if the given value is not according the provided type specification. Use this if you need typechecks even in a production build (by default all automatic runtime type checks will be skipped in production builds)

        Parameter type

        Type to check against.

        Parameter value

        Value to be checked, either a snapshot or an instance.

      function unescapeJsonPath

      unescapeJsonPath: (path: string) => string;
      • Unescape slashes and backslashes.

      function unprotect

      unprotect: (target: IAnyStateTreeNode) => void;
      • By default it is not allowed to directly modify a model. Models can only be modified through actions. However, in some cases you don't care about the advantages (like replayability, traceability, etc) this yields. For example because you are building a PoC or don't have any middleware attached to your tree.

        In that case you can disable this protection by calling unprotect on the root of your tree.

        Example:

        const Todo = types.model({
        done: false
        }).actions(self => ({
        toggle() {
        self.done = !self.done
        }
        }))
        const todo = Todo.create()
        todo.done = true // throws!
        todo.toggle() // OK
        unprotect(todo)
        todo.done = false // OK

      function walk

      walk: (
      target: IAnyStateTreeNode,
      processor: (item: IAnyStateTreeNode) => void
      ) => void;
      • Performs a depth first walk through a tree.

      Interfaces

      interface CustomTypeOptions

      interface CustomTypeOptions<S, T> {}

        property name

        name: string;
        • Friendly name

        method fromSnapshot

        fromSnapshot: (snapshot: S, env?: any) => T;
        • given a serialized value and environment, how to turn it into the target type

        method getValidationMessage

        getValidationMessage: (snapshot: S) => string;
        • a non empty string is assumed to be a validation error

        method isTargetType

        isTargetType: (value: T | S) => boolean;
        • if true, this is a converted value, if false, it's a snapshot

        method toSnapshot

        toSnapshot: (value: T) => S;
        • return the serialization of the current value

        interface IActionContext

        interface IActionContext {}

          property args

          readonly args: any[];
          • Event arguments in an array (action arguments for actions)

          property context

          readonly context: IAnyStateTreeNode;
          • Event context (node where the action was invoked)

          property id

          readonly id: number;
          • Event unique id

          property name

          readonly name: string;
          • Event name (action name for actions)

          property parentActionEvent

          readonly parentActionEvent: IMiddlewareEvent | undefined;
          • Parent action event object

          property tree

          readonly tree: IAnyStateTreeNode;
          • Event tree (root node of the node where the action was invoked)

          interface IActionRecorder

          interface IActionRecorder {}

            property actions

            actions: ReadonlyArray<ISerializedActionCall>;

              property recording

              readonly recording: boolean;

                method replay

                replay: (target: IAnyStateTreeNode) => void;

                  method resume

                  resume: () => void;

                    method stop

                    stop: () => void;

                      interface IActionTrackingMiddleware2Call

                      interface IActionTrackingMiddleware2Call<TEnv> extends Readonly<IActionContext> {}

                        property env

                        env: TEnv | undefined;

                          property parentCall

                          readonly parentCall?: IActionTrackingMiddleware2Call<TEnv>;

                            interface IActionTrackingMiddleware2Hooks

                            interface IActionTrackingMiddleware2Hooks<TEnv> {}

                              property filter

                              filter?: (call: IActionTrackingMiddleware2Call<TEnv>) => boolean;

                                property onFinish

                                onFinish: (call: IActionTrackingMiddleware2Call<TEnv>, error?: any) => void;

                                  property onStart

                                  onStart: (call: IActionTrackingMiddleware2Call<TEnv>) => void;

                                    interface IActionTrackingMiddlewareHooks

                                    interface IActionTrackingMiddlewareHooks<T> {}

                                      property filter

                                      filter?: (call: IMiddlewareEvent) => boolean;

                                        property onFail

                                        onFail: (call: IMiddlewareEvent, context: T, error: any) => void;

                                          property onResume

                                          onResume: (call: IMiddlewareEvent, context: T) => void;

                                            property onStart

                                            onStart: (call: IMiddlewareEvent) => T;

                                              property onSuccess

                                              onSuccess: (call: IMiddlewareEvent, context: T, result: any) => void;

                                                property onSuspend

                                                onSuspend: (call: IMiddlewareEvent, context: T) => void;

                                                  interface IAnyComplexType

                                                  interface IAnyComplexType extends IType<any, any, object> {}
                                                  • Any kind of complex type.

                                                  interface IAnyModelType

                                                  interface IAnyModelType extends IModelType<any, any, any, any> {}
                                                  • Any model type.

                                                  interface IAnyStateTreeNode

                                                  interface IAnyStateTreeNode extends STNValue<any, IAnyType> {}
                                                  • Represents any state tree node instance.

                                                  interface IAnyType

                                                  interface IAnyType extends IType<any, any, any> {}
                                                  • Any kind of type.

                                                  interface IArrayType

                                                  interface IArrayType<IT extends IAnyType>
                                                  extends IType<
                                                  IT['CreationType'][] | undefined,
                                                  IT['SnapshotType'][],
                                                  IMSTArray<IT>
                                                  > {}

                                                  method hooks

                                                  hooks: (hooks: IHooksGetter<IMSTArray<IAnyType>>) => IArrayType<IT>;

                                                    interface IComplexType

                                                    interface IComplexType<C, S, T> extends IType<C, S, T & object> {}
                                                    • A complex type.

                                                      Deprecated

                                                      just for compatibility with old versions, could be deprecated on the next major version

                                                    interface IJsonPatch

                                                    interface IJsonPatch {}
                                                    • https://tools.ietf.org/html/rfc6902 http://jsonpatch.com/

                                                    property op

                                                    readonly op: 'replace' | 'add' | 'remove';

                                                      property path

                                                      readonly path: string;

                                                        property value

                                                        readonly value?: any;

                                                          interface IMapType

                                                          interface IMapType<IT extends IAnyType>
                                                          extends IType<
                                                          IKeyValueMap<IT['CreationType']> | undefined,
                                                          IKeyValueMap<IT['SnapshotType']>,
                                                          IMSTMap<IT>
                                                          > {}

                                                          method hooks

                                                          hooks: (hooks: IHooksGetter<IMSTMap<IT>>) => IMapType<IT>;

                                                            interface IMaybe

                                                            interface IMaybe<IT extends IAnyType>
                                                            extends IMaybeIType<IT, undefined, undefined> {}

                                                            interface IMaybeIType

                                                            interface IMaybeIType<IT extends IAnyType, C, O>
                                                            extends IType<
                                                            IT['CreationType'] | C,
                                                            IT['SnapshotType'] | O,
                                                            IT['TypeWithoutSTN'] | O
                                                            > {}

                                                            interface IMaybeNull

                                                            interface IMaybeNull<IT extends IAnyType>
                                                            extends IMaybeIType<IT, null | undefined, null> {}

                                                            interface IMiddlewareEvent

                                                            interface IMiddlewareEvent extends IActionContext {}

                                                              property allParentIds

                                                              readonly allParentIds: number[];
                                                              • Id of all events, from root until current (excluding current)

                                                              property parentEvent

                                                              readonly parentEvent: IMiddlewareEvent | undefined;
                                                              • Parent event object

                                                              property parentId

                                                              readonly parentId: number;
                                                              • Parent event unique id

                                                              property rootId

                                                              readonly rootId: number;
                                                              • Root event unique id

                                                              property type

                                                              readonly type: IMiddlewareEventType;
                                                              • Event type

                                                              interface IModelReflectionData

                                                              interface IModelReflectionData extends IModelReflectionPropertiesData {}

                                                                property actions

                                                                actions: string[];

                                                                  property views

                                                                  views: string[];

                                                                    property volatile

                                                                    volatile: string[];

                                                                      interface IModelReflectionPropertiesData

                                                                      interface IModelReflectionPropertiesData {}

                                                                        property name

                                                                        name: string;

                                                                          property properties

                                                                          properties: {
                                                                          [K: string]: IAnyType;
                                                                          };

                                                                            interface IModelType

                                                                            interface IModelType<
                                                                            PROPS extends ModelProperties,
                                                                            OTHERS,
                                                                            CustomC = _NotCustomized,
                                                                            CustomS = _NotCustomized
                                                                            > extends IType<
                                                                            ModelCreationType2<PROPS, CustomC>,
                                                                            ModelSnapshotType2<PROPS, CustomS>,
                                                                            ModelInstanceType<PROPS, OTHERS>
                                                                            > {}

                                                                              property properties

                                                                              readonly properties: PROPS;

                                                                                method actions

                                                                                actions: <A extends ModelActions>(
                                                                                fn: (self: Instance<this>) => A
                                                                                ) => IModelType<PROPS, OTHERS & A, CustomC, CustomS>;

                                                                                  method extend

                                                                                  extend: <
                                                                                  A extends ModelActions = {},
                                                                                  V extends Object = {},
                                                                                  VS extends Object = {}
                                                                                  >(
                                                                                  fn: (self: Instance<this>) => { actions?: A; views?: V; state?: VS }
                                                                                  ) => IModelType<PROPS, OTHERS & A & V & VS, CustomC, CustomS>;

                                                                                    method named

                                                                                    named: (newName: string) => IModelType<PROPS, OTHERS, CustomC, CustomS>;

                                                                                      method postProcessSnapshot

                                                                                      postProcessSnapshot: <NewS = _CustomOrOther<CustomS, ModelSnapshotType<PROPS>>>(
                                                                                      fn: (snapshot: ModelSnapshotType2<PROPS, CustomS>) => NewS
                                                                                      ) => IModelType<PROPS, OTHERS, CustomC, NewS>;
                                                                                      • Deprecated

                                                                                        See types.snapshotProcessor

                                                                                      method preProcessSnapshot

                                                                                      preProcessSnapshot: <
                                                                                      NewC = _CustomOrOther<CustomC, ModelCreationType<ExtractCFromProps<PROPS>>>
                                                                                      >(
                                                                                      fn: (snapshot: NewC) => ModelCreationType2<PROPS, CustomC>
                                                                                      ) => IModelType<PROPS, OTHERS, NewC, CustomS>;
                                                                                      • Deprecated

                                                                                        See types.snapshotProcessor

                                                                                      method props

                                                                                      props: <PROPS2 extends ModelPropertiesDeclaration>(
                                                                                      props: PROPS2
                                                                                      ) => IModelType<
                                                                                      PROPS & ModelPropertiesDeclarationToProperties<PROPS2>,
                                                                                      OTHERS,
                                                                                      CustomC,
                                                                                      CustomS
                                                                                      >;

                                                                                        method views

                                                                                        views: <V extends Object>(
                                                                                        fn: (self: Instance<this>) => V
                                                                                        ) => IModelType<PROPS, OTHERS & V, CustomC, CustomS>;

                                                                                          method volatile

                                                                                          volatile: <TP extends object>(
                                                                                          fn: (self: Instance<this>) => TP
                                                                                          ) => IModelType<PROPS, OTHERS & TP, CustomC, CustomS>;

                                                                                            interface IMSTArray

                                                                                            interface IMSTArray<IT extends IAnyType> extends IObservableArray<IT['Type']> {}

                                                                                            method concat

                                                                                            concat: {
                                                                                            (...items: ConcatArray<IT['Type']>[]): IT['Type'][];
                                                                                            (...items: ConcatArray<ExtractCSTWithSTN<IT>>[]): IT['Type'][];
                                                                                            (...items: (IT['Type'] | ConcatArray<IT['Type']>)[]): IT['Type'][];
                                                                                            (
                                                                                            ...items: (ExtractCSTWithSTN<IT> | ConcatArray<ExtractCSTWithSTN<IT>>)[]
                                                                                            ): IT['Type'][];
                                                                                            };

                                                                                              method push

                                                                                              push: {
                                                                                              (...items: IT['Type'][]): number;
                                                                                              (...items: ExtractCSTWithSTN<IT>[]): number;
                                                                                              };

                                                                                                method splice

                                                                                                splice: {
                                                                                                (start: number, deleteCount?: number): IT['Type'][];
                                                                                                (start: number, deleteCount: number, ...items: IT['Type'][]): IT['Type'][];
                                                                                                (
                                                                                                start: number,
                                                                                                deleteCount: number,
                                                                                                ...items: ExtractCSTWithSTN<IT>[]
                                                                                                ): IT['Type'][];
                                                                                                };

                                                                                                  method unshift

                                                                                                  unshift: {
                                                                                                  (...items: IT['Type'][]): number;
                                                                                                  (...items: ExtractCSTWithSTN<IT>[]): number;
                                                                                                  };

                                                                                                    interface IMSTMap

                                                                                                    interface IMSTMap<IT extends IAnyType> {}

                                                                                                    property [Symbol.toStringTag]

                                                                                                    [Symbol.toStringTag]: 'Map';

                                                                                                      property size

                                                                                                      readonly size: number;

                                                                                                        method [Symbol.iterator]

                                                                                                        [Symbol.iterator]: () => IterableIterator<[string, IT['Type']]>;

                                                                                                          method clear

                                                                                                          clear: () => void;

                                                                                                            method delete

                                                                                                            delete: (key: string) => boolean;

                                                                                                              method entries

                                                                                                              entries: () => IterableIterator<[string, IT['Type']]>;

                                                                                                                method forEach

                                                                                                                forEach: (
                                                                                                                callbackfn: (value: IT['Type'], key: string, map: this) => void,
                                                                                                                thisArg?: any
                                                                                                                ) => void;

                                                                                                                  method get

                                                                                                                  get: (key: string) => IT['Type'] | undefined;

                                                                                                                    method has

                                                                                                                    has: (key: string) => boolean;

                                                                                                                      method intercept

                                                                                                                      intercept: (handler: any) => any;

                                                                                                                        method keys

                                                                                                                        keys: () => IterableIterator<string>;

                                                                                                                          method merge

                                                                                                                          merge: (
                                                                                                                          other:
                                                                                                                          | IMSTMap<IType<any, any, IT['TypeWithoutSTN']>>
                                                                                                                          | IKeyValueMap<ExtractCSTWithSTN<IT>>
                                                                                                                          | any
                                                                                                                          ) => this;
                                                                                                                          • Merge another object into this map, returns self.

                                                                                                                          method observe

                                                                                                                          observe: (listener: (changes: any) => void, fireImmediately?: boolean) => any;
                                                                                                                          • Observes this object. Triggers for the events 'add', 'update' and 'delete'. See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/observe for callback details

                                                                                                                          method put

                                                                                                                          put: (value: ExtractCSTWithSTN<IT>) => IT['Type'];

                                                                                                                            method replace

                                                                                                                            replace: (
                                                                                                                            values:
                                                                                                                            | IMSTMap<IType<any, any, IT['TypeWithoutSTN']>>
                                                                                                                            | IKeyValueMap<ExtractCSTWithSTN<IT>>
                                                                                                                            | any
                                                                                                                            ) => this;

                                                                                                                              method set

                                                                                                                              set: (key: string, value: ExtractCSTWithSTN<IT>) => this;

                                                                                                                                method toJSON

                                                                                                                                toJSON: () => any;

                                                                                                                                  method toString

                                                                                                                                  toString: () => string;

                                                                                                                                    method values

                                                                                                                                    values: () => IterableIterator<IT['Type']>;

                                                                                                                                      interface IOptionalIType

                                                                                                                                      interface IOptionalIType<
                                                                                                                                      IT extends IAnyType,
                                                                                                                                      OptionalVals extends ValidOptionalValues
                                                                                                                                      > extends IType<
                                                                                                                                      IT['CreationType'] | OptionalVals[number],
                                                                                                                                      IT['SnapshotType'],
                                                                                                                                      IT['TypeWithoutSTN']
                                                                                                                                      > {}

                                                                                                                                      interface IPatchRecorder

                                                                                                                                      interface IPatchRecorder {}

                                                                                                                                        property inversePatches

                                                                                                                                        inversePatches: ReadonlyArray<IJsonPatch>;

                                                                                                                                          property patches

                                                                                                                                          patches: ReadonlyArray<IJsonPatch>;

                                                                                                                                            property recording

                                                                                                                                            readonly recording: boolean;

                                                                                                                                              property reversedInversePatches

                                                                                                                                              reversedInversePatches: ReadonlyArray<IJsonPatch>;

                                                                                                                                                method replay

                                                                                                                                                replay: (target?: IAnyStateTreeNode) => void;

                                                                                                                                                  method resume

                                                                                                                                                  resume: () => void;

                                                                                                                                                    method stop

                                                                                                                                                    stop: () => void;

                                                                                                                                                      method undo

                                                                                                                                                      undo: (target?: IAnyStateTreeNode) => void;

                                                                                                                                                        interface IReferenceType

                                                                                                                                                        interface IReferenceType<IT extends IAnyComplexType>
                                                                                                                                                        extends IType<ReferenceIdentifier, ReferenceIdentifier, IT['TypeWithoutSTN']> {}

                                                                                                                                                        interface IReversibleJsonPatch

                                                                                                                                                        interface IReversibleJsonPatch extends IJsonPatch {}

                                                                                                                                                          property oldValue

                                                                                                                                                          readonly oldValue: any;

                                                                                                                                                            interface ISerializedActionCall

                                                                                                                                                            interface ISerializedActionCall {}

                                                                                                                                                              property args

                                                                                                                                                              args?: any[];

                                                                                                                                                                property name

                                                                                                                                                                name: string;

                                                                                                                                                                  property path

                                                                                                                                                                  path?: string;

                                                                                                                                                                    interface ISimpleType

                                                                                                                                                                    interface ISimpleType<T> extends IType<T, T, T> {}
                                                                                                                                                                    • A simple type, this is, a type where the instance and the snapshot representation are the same.

                                                                                                                                                                    interface ISnapshotProcessor

                                                                                                                                                                    interface ISnapshotProcessor<IT extends IAnyType, CustomC, CustomS>
                                                                                                                                                                    extends IType<
                                                                                                                                                                    _CustomOrOther<CustomC, IT['CreationType']>,
                                                                                                                                                                    _CustomOrOther<CustomS, IT['SnapshotType']>,
                                                                                                                                                                    IT['TypeWithoutSTN']
                                                                                                                                                                    > {}
                                                                                                                                                                    • A type that has its snapshots processed.

                                                                                                                                                                    interface ISnapshotProcessors

                                                                                                                                                                    interface ISnapshotProcessors<C, CustomC, S, CustomS> {}
                                                                                                                                                                    • Snapshot processors.

                                                                                                                                                                    method postProcessor

                                                                                                                                                                    postProcessor: (snapshot: S) => CustomS;
                                                                                                                                                                    • Function that transforms an output snapshot.

                                                                                                                                                                      Parameter snapshot

                                                                                                                                                                    method preProcessor

                                                                                                                                                                    preProcessor: (snapshot: CustomC) => C;
                                                                                                                                                                    • Function that transforms an input snapshot.

                                                                                                                                                                    interface IStateTreeNode

                                                                                                                                                                    interface IStateTreeNode<IT extends IAnyType = IAnyType> {}
                                                                                                                                                                    • Common interface that represents a node instance.

                                                                                                                                                                    property [$stateTreeNodeType]

                                                                                                                                                                    readonly [$stateTreeNodeType]?: [IT] | [any];

                                                                                                                                                                      interface IType

                                                                                                                                                                      interface IType<C, S, T> {}
                                                                                                                                                                      • A type, either complex or simple.

                                                                                                                                                                      property [$type]

                                                                                                                                                                      readonly [$type]: undefined;

                                                                                                                                                                      property CreationType

                                                                                                                                                                      readonly CreationType: C;
                                                                                                                                                                      • Deprecated

                                                                                                                                                                        use SnapshotIn<typeof MyType> instead.

                                                                                                                                                                      property identifierAttribute

                                                                                                                                                                      readonly identifierAttribute?: string;
                                                                                                                                                                      • Name of the identifier attribute or null if none.

                                                                                                                                                                      property name

                                                                                                                                                                      name: string;
                                                                                                                                                                      • Friendly type name.

                                                                                                                                                                      property SnapshotType

                                                                                                                                                                      readonly SnapshotType: S;
                                                                                                                                                                      • Deprecated

                                                                                                                                                                        use SnapshotOut<typeof MyType> instead.

                                                                                                                                                                      property Type

                                                                                                                                                                      readonly Type: STNValue<T, this>;
                                                                                                                                                                      • Deprecated

                                                                                                                                                                        use Instance<typeof MyType> instead.

                                                                                                                                                                      property TypeWithoutSTN

                                                                                                                                                                      readonly TypeWithoutSTN: T;
                                                                                                                                                                      • Deprecated

                                                                                                                                                                        do not use.

                                                                                                                                                                      method create

                                                                                                                                                                      create: (snapshot?: C, env?: any) => this['Type'];
                                                                                                                                                                      • Creates an instance for the type given an snapshot input.

                                                                                                                                                                        Returns

                                                                                                                                                                        An instance of that type.

                                                                                                                                                                      method describe

                                                                                                                                                                      describe: () => string;
                                                                                                                                                                      • Gets the textual representation of the type as a string.

                                                                                                                                                                      method is

                                                                                                                                                                      is: (thing: any) => thing is C | this['Type'];
                                                                                                                                                                      • Checks if a given snapshot / instance is of the given type.

                                                                                                                                                                        Parameter thing

                                                                                                                                                                        Snapshot or instance to be checked.

                                                                                                                                                                        Returns

                                                                                                                                                                        true if the value is of the current type, false otherwise.

                                                                                                                                                                      method validate

                                                                                                                                                                      validate: (thing: C, context: IValidationContext) => IValidationResult;
                                                                                                                                                                      • Run's the type's typechecker on the given value with the given validation context.

                                                                                                                                                                        Parameter thing

                                                                                                                                                                        Value to be checked, either a snapshot or an instance.

                                                                                                                                                                        Parameter context

                                                                                                                                                                        Validation context, an array of { subpaths, subtypes } that should be validated

                                                                                                                                                                        Returns

                                                                                                                                                                        The validation result, an array with the list of validation errors.

                                                                                                                                                                      interface ITypeUnion

                                                                                                                                                                      interface ITypeUnion<C, S, T>
                                                                                                                                                                      extends IType<_CustomCSProcessor<C>, _CustomCSProcessor<S>, T> {}

                                                                                                                                                                      interface ModelActions

                                                                                                                                                                      interface ModelActions {}

                                                                                                                                                                      index signature

                                                                                                                                                                      [key: string]: Function;

                                                                                                                                                                        interface ModelProperties

                                                                                                                                                                        interface ModelProperties {}

                                                                                                                                                                        index signature

                                                                                                                                                                        [key: string]: IAnyType;

                                                                                                                                                                          interface ModelPropertiesDeclaration

                                                                                                                                                                          interface ModelPropertiesDeclaration {}

                                                                                                                                                                          index signature

                                                                                                                                                                          [key: string]: ModelPrimitive | IAnyType;

                                                                                                                                                                            interface ReferenceOptionsGetSet

                                                                                                                                                                            interface ReferenceOptionsGetSet<IT extends IAnyComplexType> {}

                                                                                                                                                                              method get

                                                                                                                                                                              get: (
                                                                                                                                                                              identifier: ReferenceIdentifier,
                                                                                                                                                                              parent: IAnyStateTreeNode | null
                                                                                                                                                                              ) => ReferenceT<IT>;

                                                                                                                                                                                method set

                                                                                                                                                                                set: (
                                                                                                                                                                                value: ReferenceT<IT>,
                                                                                                                                                                                parent: IAnyStateTreeNode | null
                                                                                                                                                                                ) => ReferenceIdentifier;

                                                                                                                                                                                  interface ReferenceOptionsOnInvalidated

                                                                                                                                                                                  interface ReferenceOptionsOnInvalidated<IT extends IAnyComplexType> {}

                                                                                                                                                                                    property onInvalidated

                                                                                                                                                                                    onInvalidated: OnReferenceInvalidated<ReferenceT<IT>>;

                                                                                                                                                                                      interface UnionOptions

                                                                                                                                                                                      interface UnionOptions {}

                                                                                                                                                                                        property dispatcher

                                                                                                                                                                                        dispatcher?: ITypeDispatcher;

                                                                                                                                                                                          property eager

                                                                                                                                                                                          eager?: boolean;

                                                                                                                                                                                            Type Aliases

                                                                                                                                                                                            type IDisposer

                                                                                                                                                                                            type IDisposer = () => void;
                                                                                                                                                                                            • A generic disposer.

                                                                                                                                                                                            type IMiddlewareEventType

                                                                                                                                                                                            type IMiddlewareEventType =
                                                                                                                                                                                            | 'action'
                                                                                                                                                                                            | 'flow_spawn'
                                                                                                                                                                                            | 'flow_resume'
                                                                                                                                                                                            | 'flow_resume_error'
                                                                                                                                                                                            | 'flow_return'
                                                                                                                                                                                            | 'flow_throw';

                                                                                                                                                                                              type IMiddlewareHandler

                                                                                                                                                                                              type IMiddlewareHandler = (
                                                                                                                                                                                              actionCall: IMiddlewareEvent,
                                                                                                                                                                                              next: (actionCall: IMiddlewareEvent, callback?: (value: any) => any) => void,
                                                                                                                                                                                              abort: (value: any) => void
                                                                                                                                                                                              ) => any;

                                                                                                                                                                                                type Instance

                                                                                                                                                                                                type Instance<T> = T extends {
                                                                                                                                                                                                [$type]: undefined;
                                                                                                                                                                                                Type: any;
                                                                                                                                                                                                }
                                                                                                                                                                                                ? T['Type']
                                                                                                                                                                                                : T;
                                                                                                                                                                                                • The instance representation of a given type.

                                                                                                                                                                                                type LivelinessMode

                                                                                                                                                                                                type LivelinessMode = 'warn' | 'error' | 'ignore';
                                                                                                                                                                                                • Defines what MST should do when running into reads / writes to objects that have died. - "warn": Print a warning (default). - "error": Throw an exception. - "ignore": Do nothing.

                                                                                                                                                                                                type LivelynessMode

                                                                                                                                                                                                type LivelynessMode = LivelinessMode;
                                                                                                                                                                                                • Deprecated

                                                                                                                                                                                                  use LivelinessMode instead

                                                                                                                                                                                                type ModelCreationType

                                                                                                                                                                                                type ModelCreationType<PC> = {
                                                                                                                                                                                                [P in DefinablePropsNames<PC>]: PC[P];
                                                                                                                                                                                                } &
                                                                                                                                                                                                Partial<PC> &
                                                                                                                                                                                                NonEmptyObject;

                                                                                                                                                                                                type ModelCreationType2

                                                                                                                                                                                                type ModelCreationType2<P extends ModelProperties, CustomC> = _CustomOrOther<
                                                                                                                                                                                                CustomC,
                                                                                                                                                                                                ModelCreationType<ExtractCFromProps<P>>
                                                                                                                                                                                                >;

                                                                                                                                                                                                type ModelInstanceType

                                                                                                                                                                                                type ModelInstanceType<P extends ModelProperties, O> = ModelInstanceTypeProps<P> & O;
                                                                                                                                                                                                • do not transform this to an interface or model instance type generated declarations will be longer

                                                                                                                                                                                                type ModelInstanceTypeProps

                                                                                                                                                                                                type ModelInstanceTypeProps<P extends ModelProperties> = {
                                                                                                                                                                                                [K in keyof P]: P[K]['Type'];
                                                                                                                                                                                                } &
                                                                                                                                                                                                NonEmptyObject;
                                                                                                                                                                                                • we keep this separate from ModelInstanceType to shorten model instance types generated declarations

                                                                                                                                                                                                type ModelPrimitive

                                                                                                                                                                                                type ModelPrimitive = string | number | boolean | Date;

                                                                                                                                                                                                type ModelPropertiesDeclarationToProperties

                                                                                                                                                                                                type ModelPropertiesDeclarationToProperties<
                                                                                                                                                                                                T extends ModelPropertiesDeclaration
                                                                                                                                                                                                > = T extends {
                                                                                                                                                                                                [k: string]: IAnyType;
                                                                                                                                                                                                }
                                                                                                                                                                                                ? T
                                                                                                                                                                                                : {
                                                                                                                                                                                                [K in keyof T]: T[K] extends IAnyType
                                                                                                                                                                                                ? T[K]
                                                                                                                                                                                                : T[K] extends string
                                                                                                                                                                                                ? IType<string | undefined, string, string>
                                                                                                                                                                                                : T[K] extends number
                                                                                                                                                                                                ? IType<number | undefined, number, number>
                                                                                                                                                                                                : T[K] extends boolean
                                                                                                                                                                                                ? IType<boolean | undefined, boolean, boolean>
                                                                                                                                                                                                : T[K] extends Date
                                                                                                                                                                                                ? IType<number | Date | undefined, number, Date>
                                                                                                                                                                                                : never;
                                                                                                                                                                                                };
                                                                                                                                                                                                • Unmaps syntax property declarations to a map of { propName: IType }

                                                                                                                                                                                                type ModelSnapshotType

                                                                                                                                                                                                type ModelSnapshotType<P extends ModelProperties> = {
                                                                                                                                                                                                [K in keyof P]: P[K]['SnapshotType'];
                                                                                                                                                                                                } &
                                                                                                                                                                                                NonEmptyObject;

                                                                                                                                                                                                type ModelSnapshotType2

                                                                                                                                                                                                type ModelSnapshotType2<P extends ModelProperties, CustomS> = _CustomOrOther<
                                                                                                                                                                                                CustomS,
                                                                                                                                                                                                ModelSnapshotType<P>
                                                                                                                                                                                                >;

                                                                                                                                                                                                type OnReferenceInvalidated

                                                                                                                                                                                                type OnReferenceInvalidated<STN extends IAnyStateTreeNode> = (
                                                                                                                                                                                                event: OnReferenceInvalidatedEvent<STN>
                                                                                                                                                                                                ) => void;

                                                                                                                                                                                                  type OnReferenceInvalidatedEvent

                                                                                                                                                                                                  type OnReferenceInvalidatedEvent<STN extends IAnyStateTreeNode> = {
                                                                                                                                                                                                  parent: IAnyStateTreeNode;
                                                                                                                                                                                                  invalidTarget: STN | undefined;
                                                                                                                                                                                                  invalidId: ReferenceIdentifier;
                                                                                                                                                                                                  replaceRef: (newRef: STN | null | undefined) => void;
                                                                                                                                                                                                  removeRef: () => void;
                                                                                                                                                                                                  cause: 'detach' | 'destroy' | 'invalidSnapshotReference';
                                                                                                                                                                                                  };

                                                                                                                                                                                                    type OptionalDefaultValueOrFunction

                                                                                                                                                                                                    type OptionalDefaultValueOrFunction<IT extends IAnyType> =
                                                                                                                                                                                                    | IT['CreationType']
                                                                                                                                                                                                    | IT['SnapshotType']
                                                                                                                                                                                                    | (() => ExtractCSTWithSTN<IT>);

                                                                                                                                                                                                    type ReferenceIdentifier

                                                                                                                                                                                                    type ReferenceIdentifier = string | number;
                                                                                                                                                                                                    • Valid types for identifiers.

                                                                                                                                                                                                    type ReferenceOptions

                                                                                                                                                                                                    type ReferenceOptions<IT extends IAnyComplexType> =
                                                                                                                                                                                                    | ReferenceOptionsGetSet<IT>
                                                                                                                                                                                                    | ReferenceOptionsOnInvalidated<IT>
                                                                                                                                                                                                    | (ReferenceOptionsGetSet<IT> & ReferenceOptionsOnInvalidated<IT>);

                                                                                                                                                                                                      type SnapshotIn

                                                                                                                                                                                                      type SnapshotIn<T> = T extends {
                                                                                                                                                                                                      [$type]: undefined;
                                                                                                                                                                                                      CreationType: any;
                                                                                                                                                                                                      }
                                                                                                                                                                                                      ? T['CreationType']
                                                                                                                                                                                                      : T extends IStateTreeNode<infer IT>
                                                                                                                                                                                                      ? IT['CreationType']
                                                                                                                                                                                                      : T;
                                                                                                                                                                                                      • The input (creation) snapshot representation of a given type.

                                                                                                                                                                                                      type SnapshotOrInstance

                                                                                                                                                                                                      type SnapshotOrInstance<T> = SnapshotIn<T> | Instance<T>;
                                                                                                                                                                                                      • A type which is equivalent to the union of SnapshotIn and Instance types of a given typeof TYPE or typeof VARIABLE. For primitives it defaults to the primitive itself.

                                                                                                                                                                                                        For example: - SnapshotOrInstance<typeof ModelA> = SnapshotIn<typeof ModelA> | Instance<typeof ModelA> - SnapshotOrInstance<typeof self.a (where self.a is a ModelA)> = SnapshotIn<typeof ModelA> | Instance<typeof ModelA>

                                                                                                                                                                                                        Usually you might want to use this when your model has a setter action that sets a property.

                                                                                                                                                                                                        Example:

                                                                                                                                                                                                        const ModelA = types.model({
                                                                                                                                                                                                        n: types.number
                                                                                                                                                                                                        })
                                                                                                                                                                                                        const ModelB = types.model({
                                                                                                                                                                                                        innerModel: ModelA
                                                                                                                                                                                                        }).actions(self => ({
                                                                                                                                                                                                        // this will accept as property both the snapshot and the instance, whichever is preferred
                                                                                                                                                                                                        setInnerModel(m: SnapshotOrInstance<typeof self.innerModel>) {
                                                                                                                                                                                                        self.innerModel = cast(m)
                                                                                                                                                                                                        }
                                                                                                                                                                                                        }))

                                                                                                                                                                                                      type SnapshotOut

                                                                                                                                                                                                      type SnapshotOut<T> = T extends {
                                                                                                                                                                                                      [$type]: undefined;
                                                                                                                                                                                                      SnapshotType: any;
                                                                                                                                                                                                      }
                                                                                                                                                                                                      ? T['SnapshotType']
                                                                                                                                                                                                      : T extends IStateTreeNode<infer IT>
                                                                                                                                                                                                      ? IT['SnapshotType']
                                                                                                                                                                                                      : T;
                                                                                                                                                                                                      • The output snapshot representation of a given type.

                                                                                                                                                                                                      type TypeOfValue

                                                                                                                                                                                                      type TypeOfValue<T extends IAnyStateTreeNode> = T extends IStateTreeNode<infer IT>
                                                                                                                                                                                                      ? IT
                                                                                                                                                                                                      : never;

                                                                                                                                                                                                      type TypeOrStateTreeNodeToStateTreeNode

                                                                                                                                                                                                      type TypeOrStateTreeNodeToStateTreeNode<
                                                                                                                                                                                                      T extends IAnyType | IAnyStateTreeNode
                                                                                                                                                                                                      > = T extends IType<any, any, infer TT> ? TT & IStateTreeNode<T> : T;

                                                                                                                                                                                                      type UnionStringArray

                                                                                                                                                                                                      type UnionStringArray<T extends string[]> = T[number];

                                                                                                                                                                                                      type ValidOptionalValue

                                                                                                                                                                                                      type ValidOptionalValue = string | boolean | number | null | undefined;

                                                                                                                                                                                                      type ValidOptionalValues

                                                                                                                                                                                                      type ValidOptionalValues = [ValidOptionalValue, ...ValidOptionalValue[]];

                                                                                                                                                                                                      Package Files (32)

                                                                                                                                                                                                      Dependencies (0)

                                                                                                                                                                                                      No dependencies.

                                                                                                                                                                                                      Dev Dependencies (26)

                                                                                                                                                                                                      Peer Dependencies (1)

                                                                                                                                                                                                      Badge

                                                                                                                                                                                                      To add a badge like this onejsDocs.io badgeto your package's README, use the codes available below.

                                                                                                                                                                                                      You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/mobx-state-tree.

                                                                                                                                                                                                      • Markdown
                                                                                                                                                                                                        [![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/mobx-state-tree)
                                                                                                                                                                                                      • HTML
                                                                                                                                                                                                        <a href="https://www.jsdocs.io/package/mobx-state-tree"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>