Philipp Spieß Philipp Spieß - 5 months ago 95
Javascript Question

Create subclasses with different attributes using an ImmutableJS Record

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"?

Answer

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.

Comments