#Extending the content of a class' properties (inner level inheritance?)

6 messages · Page 1 of 1 (latest)

sacred slate
#

I should note that I know how to get a similar result by simply using a separate chain of classes for this data. However this is a DX thing, so I would prefer to achieve this as described.


what i would like is to have some property on a class, say $foo, which when overridden will not simply wipe and overwrite the parent class' value of $foo, but instead merge with it in a similar way to top-level properties in class inheritance. I would like this to work all the way down the chain, such that if there's a great-great-great-grandchild of Parent it can still access the same $foo.a that Parent defines (overrides permitting).

class Parent {
  $foo = {
    a: 1,
    b: 2,
  }
  // insert magic here...
}

class Child {
  $foo = {
    c: 3,
    d: 4,
  }
  // ! important: there can't be additional magic here, as it will defeat the DX purpose of this
}

new Child().a; // 1
new Child().b; // 2
new Child().c; // 3
new Child().d; // 4

I'm happy to do anything in the private space of the Parent class to make this work - type safety is the last of my concerns so long as it works (I would like proper type inference somewhere, perhaps a getFoo method to avoid missing property warnings on $foo).

I'd even be content with writing a separate JS file and a DTS file, with the DTS claiming Parent is a class class, and the underlying JS messing around with prototypes and such. If it's stupid and it works, it's not stupid, right?


As mentioned above, I could totally just do this with a neighboring class chain. Child$foo extends Parent$foo and $foo = new Child$foo() or something. But I want to avoid requiring the authors of Child and any further derived classes from having to do additional work.

If there's a name for this I'd also like to know. I've been calling it "inner level inheritance" and variations of, but googling those terms gets me nowhere.

paper kraken
#

you don't need separate js and dts
ts = js + dts

#

you can theoretically export "incorrect" declarations

#

If there's a name for this I'd also like to know. I've been calling it "inner level inheritance" and variations of, but googling those terms gets me nowhere.
right, because that's not exactly a thing

#

could you just make $foo a map or something like that? that would make it much easier and safer (since this is not a typical pattern, if there's issues then fixing them is going to be a lot harder than otherwise)

#

anyways, yeah you could do it at runtime with a setter and Object.assign