We use ES6 and immutable.js to create classes, that are immutable.
class Animal extends Record({foo: ""});
How can I inherit from Animal and add custom properties, but still be able to use it as an immutable Record
?
class Animal extends Animal {}; // How to add the key "bar"?
The Record
method locks the created type to the defaultValues
and cannot be used to extend the properties any further. This is one of the gripes I mentioned here.
If you are not too bent on checking inheritance at runtime (instanceof
), then you can do this -
let foo = {foo: ""};
class Animal extends Immutable.Record(foo){}
let bar = {bar: ""};
class Mammals extends Immutable.Record(Object.assign({}, foo, bar)){}
Although not a substitute of true inheritance, it lets you reuse the schemas a bit. Methods won't be inherited this way.
We can make use of mixins here.
const PersonMixin = Base => class extends Base {
grew(years) {
return this.set("age", this.age + years); //returns a new Person, which is fine
}
};
const PersonBase = PersonMixin(new Immutable.Record({name: null, age: null}));
class Person extends PersonBase {}
const AcademicanBase = PersonMixin(new Immutable.Record({name: null, age: null, title: null}));
class Academician extends AcademicanBase {
constructor({name, age, title}) {
super({name, age, title});
}
}
var a = new Academician({name: "Bob", age: 50, title: "Assoc. Prof"});
console.log(a);
console.log(a.grew(10).age); //grew works
a.title = "Prof"; //the error "Cannot set on an immutable record" received.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With