immuts
Type-safe, generic immutable datastructure for Typescript. Does not require manually setting JS paths ["a", "b", "c"] and allows TS autocompleted drilldown.
Changelog
- 2.1.0 - Adding some array helpers
- 2.0.1 - Vastly simplified
- 0.4.5 - Added some methods for dealing with native arrays
- 0.4.0 - Removed incomplete immutablejs adapter for now
- 0.3.0 - Improved support for working with arrays and maps
Usage
Simple
interface IA {
id: number;
name: string;
}
let a1 = makeImmutable<IA>({
id: 42,
name: "foo"
});
let a2 = a1.__set(x => x.id, 23);
let a3 = a2.__set(x => x.id, "23");
Updating multiple properties
interface IA {
id: number;
name: string;
}
interface IB {
a1: IA;
a2: IA;
}
interface IC {
b: IB;
}
let c = makeImmutable<IC>({
b: {
a1: {
id: 42,
name: "foo"
},
a2: {
id: 23,
name: "bar"
}
}
});
let c2 = c.__set(x => x.b.a1, x => ({
...x,
id: 23
}));
Nested
The integration is most valuable when used with a nested object:
interface IA {
id: number;
name: string;
}
interface IB {
a1: IA;
a2: IA;
}
interface IC {
b: IB;
}
let c = makeImmutable<IC>({
b: {
a1: {
id: 42,
name: "foo"
},
a2: {
id: 23,
name: "bar"
}
}
});
let c2 = c.__set(x => x.b.a1.id, 12);
when you execute this:
let c2 = c.__set(x => x.b.a1.id, 12);
the root, b, and a1 will be automatically cloned, before the new id is assigned to a1. And again, everything is type-safe, something like
let c4 = c.__set(x => x.b.a1.id, "12");
would result in a compiler error, because the types of id and "12" do not match.
Maps
Add element
const c1 = makeImmutable({
foo: {
"a": 42,
"b": 23
}
});
const c2 = c.__set(x => x.foo, x => ({
...x,
"c": 11
}));
Remove element
const c1 = makeImmutable({
foo: {
"a": 42,
"b": 23
}
});
const p = "b";
const c2 = c.__set(x => x.foo, ({ [p], ...r }) => r);
Arrays
immuts includes a few helpers for common array operations, returning new versions of the modified arrays: push, pop, splice, remove.
const c1 = makeImmutable({
foo: [1, 2]
});
const c2 = c1.__set(x => x.foo, x => push(x, 3));
const c3 = c2.__set(x => x.foo, x => remove(x, 1));
Limitations
Internet Explorer and undefined
To build up the property path (i.__set(x => x.a.b.c) needs to be captured into ["a", "b", "c"]) the library relies on the ES6 Proxy object. In browsers where this is not suppored (mainly all versions of Internet Explorer) a fallback is used using Object.defineProperty.
This method does not deal correctly with optional properties, so something like this:
interface IA {
foo?: string;
bar: number;
}
let i = new Immutable<IA>({
bar: 42
});
i.__set(x => x.foo, "test2");
would fail because foo did not exist at the time of creation. If you don't target Internet Explorer this will not be an issue and everything should work just fine, otherwise do not use optional properties, initialize to null.