Possible to extend a generic class using parent ConstructorParameters as params to the child class constructor?

Say I have the following generic class, which has two fields: one a string, and the other a totally arbitrary generic--whatever I want it to be at instantiation:

class Parent<T> {
    stringField: String
    genericField: T;

    constructor(stringField: String, genericField: T) {
        this.stringField = stringField;
        this.genericField = genericField;

Instantiating this works as expected, e.g. new Parent("hello", "world").genericField provides intellisense for a string, new Parent("hello", 10000).genericField provides intellisense for a number, etc.

Now let's say that I want to extend Parent. This new subclass constructor should take one additional parameter not present in the Parent constructor, in addition to both the values of stringField and genericField.

However, I don't want to just copy-paste the Parent parameters, as that's not scalable if I ever need to change Parent. So instead, I'd like to use the ConstructorParameters utility type to infer those redundant parameters and pass them to the super call automatically, similar to this:

class Child<G> extends Parent<G> {
    numberField: Number;

    constructor(numberField: Number, ...params:ConstructorParameters<typeof Parent>) {
        this.numberField = numberField;

However, this does not work as expected. The above call to super in the Child class produces the following compiler error: Argument of type 'unknown' is not assignable to parameter of type 'G'. 'G' could be instantiated with an arbitrary type which could be unrelated to 'unknown'.

And indeed, writing new Child(22, "hello", "world").genericField does not provide intellisense for a string, as genericField is always of type unknown here, when I want it to be whatever type I pass to it, just as when I instantiate Parent.

Read more here: https://stackoverflow.com/questions/68415541/possible-to-extend-a-generic-class-using-parent-constructorparameters-as-params

Content Attribution

This content was originally published by user3781737 at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: