Home > Software engineering >  How to make a generic parent constructor that accepts object with keys of child class?
How to make a generic parent constructor that accepts object with keys of child class?

Time:01-16

I'd like to make a base class that defines a constructor that allows all the keys of the child class to be passed, but this is unavailable in constructors. Here's what I'd like to achieve:

class BaseClass {
  constructor(props: {[key in keyof typeof this]?: typeof this[key]}) {
    Object.assign(this, props)
  }
}

class User extends BaseClass {
  name: string;
  age: number;
}

const user = new User({name: "John"});

But this errors with:

test.ts:2:60 - error TS2333: 'this' cannot be referenced in constructor arguments.

2   constructor(props: { [key in keyof typeof this]?: typeof this[key] }) {

Is there a way to achieve this? I'm not satisfied with any solutions where I have to supply any information about the child classes in the parent class' constructor.

CodePudding user response:

As you noticed, it is currently not allowed to use the polymorphic this type in constructor parameters. There is an open feature request for such support at microsoft/TypeScript#38038. It's open and marked as "awaiting more feedback", so anyone who is interested in seeing this happen might want to go there, give the issue a

  • Related