Philipp Spiess
Philipp Spiess

Reputation: 3271

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

Upvotes: 5

Views: 1031

Answers (3)

Bender
Bender

Reputation: 647

I've ended up with this, hope it'll be helpful for some one.

// @flow
import type {RecordFactory, RecordOf} from "immutable";
import {Record} from "immutable";

type OneProps = {|
    key: boolean
|};
const oneDefaults: OneProps = {
    key: false
};
type One = RecordOf<OneProps>;
const oneItemBuilder: RecordFactory<OneProps> = Record(oneDefaults);

type TwoProps = {|
    ...OneProps,
    moreKeys: string
|};
const twoDefaults: TwoProps = {
    ...oneDefaults,
    moreKeys: "more"
};
type Two = RecordOf<TwoProps>;
const twoItemBuilder: RecordFactory<TwoProps> = Record(twoDefaults);

const oneItem: One = oneItemBuilder();
const twoItem: Two = twoItemBuilder({moreKeys: "more keys"});

Upvotes: 1

Yavuz Mester
Yavuz Mester

Reputation: 367

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.

Upvotes: 1

hazardous
hazardous

Reputation: 10837

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.

Upvotes: 3

Related Questions