immutable-class
This library provides helper functions to extend class-transformer
functionality to create immutable classes. It also provides helper functions to work with immutable classes using immer
.
fromJSON
Create an immutable class from a JSON object.
class Test {
readonly foo!: string;
readonly bar?: string
}
const cls = fromJSON(Test, { foo: 'asdf' });
toJSON
Convert a class to an immutable plain object.
class Test {
foo!: string;
bar?: string
}
const cls = new Test();
const emptyJson = toJSON(cls);
cls.foo = 'abc'
cls.bar = '123'
const setJson = toJSON(cls)
deserialize
Create an immutable class from a JSON string.
class Test {
readonly foo!: string;
readonly bar?: string
}
const cls = fromJSON(Test, `{ "foo": "asdf" }`);
deserializeArray
Create an array of immutable classes from a JSON string.
class Test {
readonly foo!: string;
readonly bar?: string
}
const cls = fromJSON(Test, `[{ "foo": "asdf" }]`);
serialize
Convert a class to an immutable plain object.
class Test {
foo!: string;
bar?: string
}
const cls = new Test();
const emptyJson = toJSON(cls);
cls.foo = 'abc'
cls.bar = '123'
const setJson = toJSON(cls)
clone
Clone an existing immutable class.
class Test {
foo!: string;
bar?: string
}
const cls = new Test();
cls.foo = 'test'
const copy = clone(cls)
update
Update an immutable class. This function will leave the original class unmodified and return an updated copy of the class. Note that classes must be marked with "[immerable]: true" in order to use this function.
class Test {
[immerable] = true;
readonly foo!: string;
readonly bar?: string
}
const cls = create(Test)
const updated = update(cls, x => {
x.foo = 'abc'
})
patch
Patch an immutable class with a JSON value. This function will leave the original class unmodified and return an updated copy of the class. Note that classes must be marked with "[immerable]: true" in order to use this function.
class Test {
[immerable] = true;
readonly foo!: string;
readonly bar?: string
}
const cls = create(Test)
const patched = patch(cls, { foo: 'abc' })
Contributing
Running unit tests
Run nx test immutable-class
to execute the unit tests via
Jest.- immutable-class