-
Notifications
You must be signed in to change notification settings - Fork 25
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
How to provide default/fixed value for inheriting class? #515
Comments
I just released v1.6.0, which removes the restriction of not being able to redeclare a property on an extended model. Note that it is now on the user side to make sure the base and the extended properties are compatible (basically kept the same). If care is not taken the type of the property might become "never", be wrong, or it might fail in runtime. example:
does that address your issue? |
Wow that's fast :-)
Typescript says:
BTW: thank you @xaviergonz , you have made a great tool!!! |
I'm afraid changing the type itself when inheriting does not get along well with typescript :-/ I don't know if you share lots of logic, but you could alternatively do this (not saying it is better than your current method though, it is more like a mixing): const props = {
x: prop<number>(),
y: prop<number>(),
} as const
function getSum2d(this: Point) {
return this.x + this.y
}
@model("MyApp/Point")
class Point extends Model(props) {
getSum2d = getSum2d
}
@model("MyApp/Point3d")
class Point3d extends Model({
...props,
y: prop(100), // this overrides the default value
z: prop(3),
}) {
getSum2d = getSum2d
}
const p1: Point3d = new Point3d({
x: 1,
y: 2,
z: 3, // ok
})
const p2: Point3d = new Point3d({
x: 1, // ok
}) |
Aaah that's very interesting, thank you so much for your help Xavier! I'm rather new to the whole typescript ecosystem, so these kind of tricks did not occur to me right away. I imagined there could be some super hacky magic with Omit on the parameters of ExtendedModel, but that's speculation, and in fact it's really not a big deal for me at the moment. Feel free to close this issue! |
For simplicity, I will take the example from https://mobx-keystone.js.org/class-models/#inheritance:
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:
But this is a lot of type-specific boilerplate. Is there a more idiomatic way to do this?
The text was updated successfully, but these errors were encountered: