Typescript constructor parameters based on class & subclass properties

Viewed 83

Let's suppose I'm looking to reuse some basic constructor in subclasses but its parameter will depend on the properties of the subclass.

Here is a basic (non-working) example of what I'm trying to achieve.

class Foo {
    a: string = 'a'

    constructor(params?: { [key in keyof this]: this[key] }) { // this doesn't work as 'this' is not permited static members. 
        Object.assign(this, params)
    }
}

class Bar extends Foo {
    b: string = 'b'

    // constructor inherited accepting { a: string, b: string }
}

const myFoo = new Foo({ a: 'foo' })
const myBar = new Bar({ a: 'foo', b: 'bar' })

Is there some kind of way to do it in TS ?

Playground

1 Answers

For Foo, you could use params?: Foo and then new Foo({a: "ayy"}) would work, but Bar would expect a Foo, not a Bar.

Unfortunately, I don't think there's anything you can do to change that other than provide a constructor in Bar. That constructor doesn't have to do much of course, just super(params).

class Foo {
    a: string = "a";

    constructor(params?: Foo) {
        Object.assign(this, params);
    }
}

class Bar extends Foo {
    b: string = "b";

    constructor(params?: Bar) {
        super(params);
    }
}

Playground link

It would be nice if params?: typeof this (or some other derivative of it) would work (and handle the change in meaning across subclasses), but that isn't the case currently.

Related