forked from mobxjs/mobx-state-tree
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAPI.md.tmp
More file actions
959 lines (635 loc) · 27.1 KB
/
API.md.tmp
File metadata and controls
959 lines (635 loc) · 27.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
<!-- Generated by documentation.js. Update this documentation by updating the source code. -->
### Table of Contents
- [addDisposer](#adddisposer)
- [addMiddleware](#addmiddleware)
- [applyAction](#applyaction)
- [applyPatch](#applypatch)
- [applySnapshot](#applysnapshot)
- [asReduxStore](#asreduxstore)
- [clone](#clone)
- [ComplexType](#complextype)
- [ComplexType](#complextype-1)
- [ComplexType](#complextype-2)
- [ComplexType](#complextype-3)
- [ComplexType](#complextype-4)
- [connectReduxDevtools](#connectreduxdevtools)
- [destroy](#destroy)
- [detach](#detach)
- [escapeJsonPath](#escapejsonpath)
- [getChildType](#getchildtype)
- [getEnv](#getenv)
- [getParent](#getparent)
- [getPath](#getpath)
- [getPathParts](#getpathparts)
- [getRelativePath](#getrelativepath)
- [getRoot](#getroot)
- [getSnapshot](#getsnapshot)
- [getType](#gettype)
- [hasParent](#hasparent)
- [Identifier](#identifier)
- [IdentifierCache](#identifiercache)
- [isAlive](#isalive)
- [isProtected](#isprotected)
- [isRoot](#isroot)
- [isStateTreeNode](#isstatetreenode)
- [Node](#node)
- [onAction](#onaction)
- [onPatch](#onpatch)
- [onSnapshot](#onsnapshot)
- [process](#process)
- [protect](#protect)
- [recordActions](#recordactions)
- [recordPatches](#recordpatches)
- [resolveIdentifier](#resolveidentifier)
- [resolvePath](#resolvepath)
- [revertPatch](#revertpatch)
- [StoredReference](#storedreference)
- [tryResolve](#tryresolve)
- [Type](#type)
- [Type](#type-1)
- [Type](#type-2)
- [Type](#type-3)
- [Type](#type-4)
- [Type](#type-5)
- [Type](#type-6)
- [Type](#type-7)
- [Type](#type-8)
- [types.array](#typesarray)
- [types.boolean](#typesboolean)
- [types.compose](#typescompose)
- [types.Date](#typesdate)
- [types.enumeration](#typesenumeration)
- [types.frozen](#typesfrozen)
- [types.identifier](#typesidentifier)
- [types.late](#typeslate)
- [types.literal](#typesliteral)
- [types.map](#typesmap)
- [types.maybe](#typesmaybe)
- [types.model](#typesmodel)
- [types.null](#typesnull)
- [types.number](#typesnumber)
- [types.optional](#typesoptional)
- [types.reference](#typesreference)
- [types.refinement](#typesrefinement)
- [types.string](#typesstring)
- [types.undefined](#typesundefined)
- [types.union](#typesunion)
- [unescapeJsonPath](#unescapejsonpath)
- [unprotect](#unprotect)
- [walk](#walk)
## addDisposer
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.
**Parameters**
- `target` **IStateTreeNode**
- `disposer`
**Examples**
````javascript
```javascript
const Todo = types.model({
title: types.string
}, {
afterCreate() {
const autoSaveDisposer = reaction(
() => getSnapshot(this),
snapshot => sendSnapshotToServerSomehow(snapshot)
)
// stop sending updates to server if this
// instance is destroyed
addDisposer(this, autoSaveDisposer)
}
})
```
````
## addMiddleware
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](docs/middleware.md)
**Parameters**
- `target` **IStateTreeNode**
- `middleware`
Returns **IDisposer**
## applyAction
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.
**Parameters**
- `target` **[Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)**
- `actions` **[Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)<IActionCall>**
- `options` **IActionCallOptions?**
## applyPatch
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.
**Parameters**
- `target` **[Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)**
- `patch` **IJsonPatch**
## applySnapshot
Applies a snapshot to a given model instances. Patch and snapshot listeners will be invoked as usual.
**Parameters**
- `target` **[Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)**
- `snapshot` **[Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)**
## asReduxStore
Creates a tiny proxy around a MST tree that conforms to the redux store api.
This makes it possible to use MST inside a redux application.
See the [redux-todomvc example](https://github.com/mobxjs/mobx-state-tree/blob/e9e804c8c43e1edde4aabbd52675544e2b3a905b/examples/redux-todomvc/src/index.js#L20) for more details.
**Parameters**
- `model` **any**
- `middlewares` **...[Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)<MiddleWare>**
Returns **IReduxStore**
## clone
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_
**Parameters**
- `source` **T**
- `keepEnvironment` **([boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean) | any)** 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 **T**
## ComplexType
## ComplexType
## ComplexType
## ComplexType
## ComplexType
## connectReduxDevtools
Connects a MST tree to the Redux devtools.
See this [example](https://github.com/mobxjs/mobx-state-tree/blob/e9e804c8c43e1edde4aabbd52675544e2b3a905b/examples/redux-todomvc/src/index.js#L21) for a setup example.
**Parameters**
- `remoteDevDep` **any**
- `model` **any**
## destroy
Removes a model element from the state tree, and mark it as end-of-life; the element should not be used anymore
**Parameters**
- `target`
## detach
Removes a model element from the state tree, and let it live on as a new state tree
**Parameters**
- `target`
## escapeJsonPath
escape slashes and backslashes
<http://tools.ietf.org/html/rfc6901>
**Parameters**
- `str`
## getChildType
Returns the _declared_ type of the given sub property of an object, array or map.
**Parameters**
- `object` **IStateTreeNode**
- `child` **[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)**
**Examples**
````javascript
```typescript
const Box = types.model({ x: 0, y: 0 })
const box = Box.create()
console.log(getChildType(box, "x").name) // 'number'
```
````
Returns **IType<any, any>**
## getEnv
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)
**Parameters**
- `target` **IStateTreeNode**
Returns **any**
## getParent
Returns the immediate parent of this object, or null.
Note that the immediate parent can be either an object, map or array, and
doesn't necessarily refer to the parent model
**Parameters**
- `target` **[Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)**
- `depth` **[number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number)** = 1, how far should we look upward?
Returns **any**
## getPath
Returns the path of the given object in the model tree
**Parameters**
- `target` **[Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)**
Returns **[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)**
## getPathParts
Returns the path of the given object as unescaped string array
**Parameters**
- `target` **[Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)**
Returns **[Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)<[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)>**
## getRelativePath
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
**Parameters**
- `base` **IStateTreeNode**
- `target` **IStateTreeNode**
Returns **[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)**
## getRoot
Given an object in a model tree, returns the root object of that tree
**Parameters**
- `target` **[Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)**
Returns **any**
## getSnapshot
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.
**Parameters**
- `target` **[Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)**
Returns **any**
## getType
Returns the _actual_ type of the given tree node. (Or throws)
**Parameters**
- `object` **IStateTreeNode**
Returns **IType<S, T>**
## hasParent
Given a model instance, returns `true` if the object has a parent, that is, is part of another object, map or array
**Parameters**
- `target` **[Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)**
- `depth` **[number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number)** = 1, how far should we look upward?
Returns **[boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)**
## Identifier
## IdentifierCache
## isAlive
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
**Parameters**
- `target` **IStateTreeNode**
Returns **[boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)**
## isProtected
Returns true if the object is in protected mode, @see protect
**Parameters**
- `target`
## isRoot
Returns true if the given object is the root of a model tree
**Parameters**
- `target` **[Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)**
Returns **[boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)**
## isStateTreeNode
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`.
**Parameters**
- `value` **any**
## Node
## onAction
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.
**Parameters**
- `target` **IStateTreeNode**
- `listener`
Returns **IDisposer**
## onPatch
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.
**Parameters**
- `target` **[Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)** the model instance from which to receive patches
- `callback`
- `includeOldValue`
- `boolean` **includeOldValue** if oldValue is included in the patches, they can be inverted. However patches will become much bigger and might not be suitable for efficient transport
Returns **IDisposer** function to remove the listener
## onSnapshot
Registeres a function that is invoked whenever a new snapshot for the given model instance is available.
The listener will only be fire at the and of the current MobX (trans)action.
See [snapshots](https://github.com/mobxjs/mobx-state-tree#snapshots) for more details.
**Parameters**
- `target` **[Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)**
- `callback`
Returns **IDisposer**
## process
See [asynchronous actions](https://github.com/mobxjs/mobx-state-tree/blob/master/docs/async-actions.md).
**Parameters**
- `asyncAction`
Returns **[Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)**
## protect
The inverse of `unprotect`
**Parameters**
- `target` **IStateTreeNode**
## recordActions
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:
```typescript
export interface IActionRecorder {
// the recorded actions
actions: ISerializedActionCall[]
// stop recording actions
stop(): any
// apply all the recorded actions on the given object
replay(target: IStateTreeNode): any
}
```
**Parameters**
- `subject` **IStateTreeNode**
Returns **IPatchRecorder**
## recordPatches
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:
```typescript
export interface IPatchRecorder {
// the recorded patches
patches: IJsonPatch[]
// the same set of recorded patches, but without undo information, making them smaller and compliant with json-patch spec
cleanPatches: IJSonPatch[]
// stop recording patches
stop(target?: IStateTreeNode): any
// apply all the recorded patches on the given target (the original subject if omitted)
replay(target?: IStateTreeNode): any
// reverse apply the recorded patches on the given target (the original subject if omitted)
// stops the recorder if not already stopped
undo(): void
}
```
**Parameters**
- `subject` **IStateTreeNode**
Returns **IPatchRecorder**
## resolveIdentifier
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.
**Parameters**
- `type` **IType<any, any>**
- `target` **IStateTreeNode**
- `identifier` **([string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) \| [number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number))**
Returns **any**
## resolvePath
Resolves a path relatively to a given object.
Returns undefined if no value can be found.
**Parameters**
- `target` **[Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)**
- `path` **[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)** escaped json path
Returns **any**
## revertPatch
The inverse function of apply patch.
Given a patch or set of patches, restores the target to the state before the patches where produced.
The inverse patch is computed, and all the patches are applied in reverse order, basically 'rewinding' the target,
so that conceptually the following holds for any set of patches:
`getSnapshot(x) === getSnapshot(revertPatch(applyPatches(x, patches), patches))`
Note: Reverting patches will generate a new set of patches as side effect of applying the patches.
Note: only patches that include `oldValue` information are suitable for reverting. Such patches can be generated by passing `true` as second argument when attaching an `onPatch` listener.
**Parameters**
- `target`
- `patch`
## StoredReference
## tryResolve
**Parameters**
- `target` **[Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object)**
- `path` **[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)**
Returns **any**
## Type
## Type
## Type
## Type
## Type
## Type
## Type
## Type
## Type
## types.array
Creates a index based collection type who's children are all of a uniform declared type.
This type will always produce [observable arrays](https://mobx.js.org/refguide/array.html)
**Parameters**
- `subtype` **IType<S, T>**
**Examples**
````javascript
```javascript
const Todo = types.model({
task: types.string
})
const TodoStore = types.model({
todos: types.array(Todo)
})
const s = TodoStore.create({ todos: [] })
s.todos.push({ task: "Grab coffee" })
console.log(s.todos[0]) // prints: "Grab coffee"
```
````
Returns **IComplexType<[Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)<S>, IObservableArray<T>>**
## types.boolean
Creates a type that can only contain a boolean value.
This type is used for boolean values by default
**Examples**
````javascript
```javascript
const Thing = types.model({
isCool: types.boolean,
isAwesome: false
})
```
````
## types.compose
Composes a new model from one or more existing model types.
This method can be invoked in two forms:
Given 2 or more model types, the types are composed into a new Type.
## types.Date
Creates a type that can only contain a javascript Date value.
**Examples**
````javascript
```javascript
const LogLine = types.model({
timestamp: types.Date,
})
LogLine.create({ timestamp: new Date() })
```
````
## types.enumeration
Can be used to create an string based enumeration.
(note: this methods is just sugar for a union of string literals)
**Parameters**
- `name` **[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)** descriptive name of the enumeration (optional)
- `options` **[Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)<[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)>** possible values this enumeration can have
**Examples**
````javascript
```javascript
const TrafficLight = types.model({
color: types.enum("Color", ["Red", "Orange", "Green"])
})
```
````
Returns **ISimpleType<[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)>**
## types.frozen
Frozen can be used to story any value that is serializable in itself (that is valid JSON).
Frozen values need to be immutable or treated as if immutable.
Values stored in frozen will snapshotted as-is by MST, and internal changes will not be tracked.
This is useful to store complex, but immutable values like vectors etc. It can form a powerful bridge to parts of your application that should be immutable, or that assume data to be immutable.
**Examples**
````javascript
```javascript
const GameCharacter = types.model({
name: string,
location: types.frozen
})
const hero = new GameCharacter({
name: "Mario",
location: { x: 7, y: 4 }
})
hero.location = { x: 10, y: 2 } // OK
hero.location.x = 7 // Not ok!
```
````
## types.identifier
Identifier are used to make references, lifecycle events and reconciling works.
Inside a state tree, for each type can exist only one instance for each given identifier.
For example there could'nt be 2 instances of user with id 1. If you need more, consider using references.
Identifier can be used only as type property of a model.
This type accepts as parameter the value type of the identifier field that can be either string or number.
**Parameters**
- `baseType` **IType<T, T>**
**Examples**
```javascript
const Todo = types.model("Todo", {
id: types.identifier(types.string),
title: types.string
})
```
Returns **IType<T, T>**
## types.late
Defines a type that gets implemented later. This is usefull when you have to deal with circular dependencies.
Please notice that when defining circular dependencies TypeScript is'nt smart enought to inference them.
You need to declare an interface to explicit the return type of the late parameter function.
```typescript
interface INode {
childs: INode[]
}
// TypeScript is'nt smart enough to infer self referencing types.
const Node = types.model({
childs: types.optional(types.array(types.late<any, INode>(() => Node)), [])
})
```
**Parameters**
- `nameOrType`
- `maybeType`
- `name` **[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)?** The name to use for the type that will be returned.
- `type` **ILateType<S, T>** A function that returns the type that will be defined.
Returns **IType<S, T>**
## types.literal
The literal type will return a type that will match only the exact given type.
The given value must be a primitive, in order to be serialized to a snapshot correctly.
You can use literal to match exact strings for example the exact male or female string.
**Parameters**
- `value` **S** The value to use in the strict equal check
**Examples**
```javascript
const Person = types.model({
name: types.string,
gender: types.union(types.literal('male'), types.literal('female'))
})
```
Returns **ISimpleType<S>**
## types.map
Creates a key based collection type who's children are all of a uniform declared type.
If the type stored in a map has an identifier, it is mandatory to store the child under that identifier in the map.
This type will always produce [observable maps](https://mobx.js.org/refguide/map.html)
**Parameters**
- `subtype` **IType<S, T>**
**Examples**
````javascript
```javascript
const Todo = types.model({
id: types.identifier,
task: types.string
})
const TodoStore = types.model({
todos: types.map(Todo)
})
const s = TodoStore.create({ todos: [] })
s.todos.set(17, { task: "Grab coffee", id: 17 })
s.todos.put({ task: "Grab cookie", id: 18 }) // put will infer key from the identifier
console.log(s.todos.get(17)) // prints: "Grab coffee"
```
````
Returns **IComplexType<[Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)<S>, IObservableArray<T>>**
## types.maybe
Maybe will make a type nullable, and also null by default.
**Parameters**
- `type` **IType<S, T>** The type to make nullable
Returns **(IType<(S | null | [undefined](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined)), (T | null)>)**
## types.model
Creates a new model type by providing a name, properties, volatile state and actions.
See the [model type](https://github.com/mobxjs/mobx-state-tree#creating-models) description or the [getting started](https://github.com/mobxjs/mobx-state-tree/blob/master/docs/getting-started.md#getting-started-1) tutorial.
## types.null
The type of the value `null`
## types.number
Creates a type that can only contain a numeric value.
This type is used for numeric values by default
**Examples**
````javascript
```javascript
const Vector = types.model({
x: types.number,
y: 0
})
```
````
## types.optional
`types.optional` can be used to create a property with a default value.
If the given value is not provided in the snapshot, it will default to the provided `defaultValue`.
If `defaultValue` is a function, the function will be invoked for every new instance.
Applying a snapshot in which the optional value is _not_ present, causes the value to be reset
**Parameters**
- `type`
- `defaultValueOrFunction`
**Examples**
````javascript
```javascript
const Todo = types.model({
title: types.optional(types.string, "Test"),
done: types.optional(types.boolean, false),
created: types.optional(types.Date, () => new Date())
})
// it is now okay to omit 'created' and 'done'. created will get a freshly generated timestamp
const todo = Todo.create({ title: "Get coffee "})
```
````
## types.reference
Creates a reference to another type, which should have defined an identifier.
See also the [reference and identifiers](https://github.com/mobxjs/mobx-state-tree#references-and-identifiers) section.
**Parameters**
- `subType`
## types.refinement
`types.refinement(baseType, (snapshot) => boolean)` creates a type that is more specific then the base type, e.g. `types.refinement(types.string, value => value.length > 5)` to create a type of strings that can only be longer then 5.
**Parameters**
- `name` **[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)**
- `type` **IType<T, T>**
Returns **IType<T, T>**
## types.string
Creates a type that can only contain a string value.
This type is used for string values by default
**Examples**
````javascript
```javascript
const Person = types.model({
firstName: types.string,
lastName: "Doe"
})
```
````
## types.undefined
The type of the value `undefined`
## types.union
types.union(dispatcher?, types...) create a union of multiple types. If the correct type cannot be inferred unambigously from a snapshot, provide a dispatcher function of the form (snapshot) => Type.
**Parameters**
- `dispatchOrType` **(ITypeDispatcher | IType<any, any>)**
- `otherTypes` **...[Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)<IType<any, any>>**
Returns **IType<any, any>**
## unescapeJsonPath
unescape slashes and backslashes
**Parameters**
- `str`
## unprotect
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, tracability, 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.
**Parameters**
- `target`
**Examples**
```javascript
const Todo = types.model({
done: false,
toggle() {
this.done = !this.done
}
})
const todo = new Todo()
todo.done = true // OK
protect(todo)
todo.done = false // throws!
todo.toggle() // OK
```
## walk
Performs a depth first walk through a tree
**Parameters**
- `target`
- `processor`