Skip to content

How to provide default/fixed value for inheriting class?  #515

@feliksik

Description

@feliksik

For simplicity, I will take the example from https://mobx-keystone.js.org/class-models/#inheritance:

@model("MyApp/Point")
class Point extends Model({
  x: prop<number>(),
  y: prop<number>(),
}) {
  get sum() {
    return this.x + this.y
  }
}

// note how `ExtendedModel` is used
@model("MyApp/Point3d")
class Point3d extends ExtendedModel(Point, {
  z: prop<number>(),
}) {

}

How can I make the Point3d have a fixed value of '12' for the x value (or at least define an optional default for the constructor)?

I guess I can make a factory method that takes only the required parameters sets it, like so:

@model("MyApp/Point3d")
class Point3d extends ExtendedModel(Point, {
  z: prop<number>(),
}) {
    static create(constructorParams: {y: number, z: number}){ // or constructorParams: Omit<ModelCreationData<Point>, "x"> & { z: number }
        return new Point3d(
            {
                ...constructorParams,
                x: 12,
            }
        )
    }
}

But this is a lot of type-specific boilerplate. Is there a more idiomatic way to do this?

Metadata

Metadata

Assignees

Labels

🍗 enhancementNew feature or request🎈 releasedA fix that should close the issue has been released📑 merged to masterFeature done and merged to master

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions