UNPKG

mobx-keystone-mindreframer

Version:

A MobX powered state management solution based on data trees with first class support for Typescript, snapshots, patches and much more

46 lines (45 loc) 1.86 kB
import type { AnyStandardType, AnyType, TypeToData } from "./schemas"; import { TypeInfo } from "./TypeChecker"; import { TypeCheckError } from "./TypeCheckError"; /** * A refinement over a given type. This allows you to do extra checks * over models, ensure numbers are integers, etc. * * Example: * ```ts * const integerType = types.refinement(types.number, (n) => { * return Number.isInteger(n) * }, "integer") * * const sumModelType = types.refinement(types.model(Sum), (sum) => { * // imagine that for some reason sum includes a number 'a', a number 'b' * // and the result * * const rightResult = sum.a + sum.b === sum.result * * // simple mode that will just return that the whole model is incorrect * return rightResult * * // this will return that the result field is wrong * return rightResult ? null : new TypeCheckError(["result"], "a+b", sum.result) * }) * ``` * * @template T Base type. * @param baseType Base type. * @param checkFn Function that will receive the data (if it passes the base type * check) and return null or false if there were no errors or either a TypeCheckError instance or * true if there were. * @returns */ export declare function typesRefinement<T extends AnyType>(baseType: T, checkFn: (data: TypeToData<T>) => TypeCheckError | null | boolean, typeName?: string): T; /** * `types.refinement` type info. */ export declare class RefinementTypeInfo extends TypeInfo { readonly baseType: AnyStandardType; readonly checkFunction: (data: any) => TypeCheckError | null | boolean; readonly typeName: string | undefined; get baseTypeInfo(): TypeInfo; constructor(thisType: AnyStandardType, baseType: AnyStandardType, checkFunction: (data: any) => TypeCheckError | null | boolean, typeName: string | undefined); }