1 | import { IType } from "../../internal";
|
2 | export interface CustomTypeOptions<S, T> {
|
3 | /** Friendly name */
|
4 | name: string;
|
5 | /** given a serialized value and environment, how to turn it into the target type */
|
6 | fromSnapshot(snapshot: S, env?: any): T;
|
7 | /** return the serialization of the current value */
|
8 | toSnapshot(value: T): S;
|
9 | /** if true, this is a converted value, if false, it's a snapshot */
|
10 | isTargetType(value: T | S): boolean;
|
11 | /** a non empty string is assumed to be a validation error */
|
12 | getValidationMessage(snapshot: S): string;
|
13 | }
|
14 | /**
|
15 | * `types.custom` - Creates a custom type. Custom types can be used for arbitrary immutable values, that have a serializable representation. For example, to create your own Date representation, Decimal type etc.
|
16 | *
|
17 | * The signature of the options is:
|
18 | * ```ts
|
19 | * export interface CustomTypeOptions<S, T> {
|
20 | * // Friendly name
|
21 | * name: string
|
22 | * // given a serialized value and environment, how to turn it into the target type
|
23 | * fromSnapshot(snapshot: S, env: any): T
|
24 | * // return the serialization of the current value
|
25 | * toSnapshot(value: T): S
|
26 | * // if true, this is a converted value, if false, it's a snapshot
|
27 | * isTargetType(value: T | S): value is T
|
28 | * // a non empty string is assumed to be a validation error
|
29 | * getValidationMessage?(snapshot: S): string
|
30 | * }
|
31 | * ```
|
32 | *
|
33 | * Example:
|
34 | * ```ts
|
35 | * const DecimalPrimitive = types.custom<string, Decimal>({
|
36 | * name: "Decimal",
|
37 | * fromSnapshot(value: string) {
|
38 | * return new Decimal(value)
|
39 | * },
|
40 | * toSnapshot(value: Decimal) {
|
41 | * return value.toString()
|
42 | * },
|
43 | * isTargetType(value: string | Decimal): boolean {
|
44 | * return value instanceof Decimal
|
45 | * },
|
46 | * getValidationMessage(value: string): string {
|
47 | * if (/^-?\d+\.\d+$/.test(value)) return "" // OK
|
48 | * return `'${value}' doesn't look like a valid decimal number`
|
49 | * }
|
50 | * })
|
51 | *
|
52 | * const Wallet = types.model({
|
53 | * balance: DecimalPrimitive
|
54 | * })
|
55 | * ```
|
56 | *
|
57 | * @param options
|
58 | * @returns
|
59 | */
|
60 | export declare function custom<S, T>(options: CustomTypeOptions<S, T>): IType<S | T, S, T>;
|