Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"?
like image 492
Philipp Spiess Avatar asked Jun 01 '16 16:06

Philipp Spiess


Video Answer


2 Answers

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.

like image 105
hazardous Avatar answered Sep 25 '22 14:09

hazardous


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.

like image 37
Yavuz Mester Avatar answered Sep 21 '22 14:09

Yavuz Mester