Subclassing with various attributes using the ImmutableJS record

We use ES6 and immutable.js to create immutable classes.

class Animal extends Record({foo: ""});

How can I inherit from Animal and add custom properties, but still can use it as immutable Record?

class Animal extends Animal {}; // How to add the key "bar"?
+5
source share
3 answers

The method Recordblocks the created type for defaultValuesand cannot be used to further extend the properties. This is one of the issues that I mentioned here .

If you are not too inclined to check inheritance at runtime ( instanceof), 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)){}

, . .

+2

mixins .



    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.

+1

I ended up with this, hopefully it will be useful for someone.

// @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"});
0
source

All Articles