typescript-immutable
immutable.js is a library for immutable data structures. However, I had a lot of trouble using immutable.js with Typescript.
The main problem was to
- maintain type-safety for
Records
as described here - handle potentially undefined elements in a
Map
(in immtable.js you can define anotSetValue
parameter inget()
andupdate()
but not on instantiation)
This package
- implements Maps, Records and Arrays.
- doesn't not have any dependencies.
Features
- Full type-safety
- If a
initialValue
(ImmutableRecord
) ornotSetValue
is set (ImmutableMap
), the type is automatically detected from that value. - If no such value is set (
ImmutableMapUndef
), you must provide the type of the stored values.
How to use
ImmutableMapUndef
; ; Map.get'someKey'; // undefined Map.set'someKey', 'string'; // type errorMap.set'someKey', 2; // okMap.set'someOtherKey', 4; // ok Map.setMany; Map.mapcurrVal * 2; Map.toArray; // [4, 8, 16, 32] Map.update'someKey', currVal! + 4; // 8 Map.clear;Map.get'someKey'; // undefined
ImmutableMap
; ; Map.get'undefinedKey'; // ImmutableRecord with {foo: 'bar', key: false} // Returns ImmutableMap with { key: ImmutableRecord with {foo: 'myString', key: false} }Map.update'key', currVal.get'foo', 'myString'; // ...other functions same as ImmutableMapUndef
ImmutableRecord
; ; Record.get'someKey'; // initialValue Record.set'someKey', 1; // type errorRecord.get'someNotExistingKey'; // type error Record.set'someKey', 'string'; // ok Record.update'someKey', currVal + '!!!'; // initialValue!!! Record.withMutations;
ImmutableArray
; ; Arr.get0; // 1;Arr.length; // 2Arr.get3; // undefinedArr.push4, 8; // ImmutableArray([1, 2, 4, 8])Arr.length; // 4Arr.mapval * 2; // ImmutableArray([2, 4, 8, 16])Arr.filterval < 9; // ImmutableArray([2, 4, 8])Arr.set2, 3; // ImmutableArray([2, 3, 8])Arr.update2, val - 4; // ImmutableArray([2, 3, 4])Arr.slice; // [2, 3, 4]Arr.indexOf3; // 1Arr.indexOfFnval > 2; // 1Arr.remove1; // ImmutableArray([2, 4])