The problem I'm having is that I have some base (generic) classes whose properties are initialized via the class's constructor. When I then go to extend this class to create a more specific class, I must re-type the same parameters that the base class's constructor has, just so I can pass them to super. If you imagine a very generic class that has many properties that are initialized via a constructor , and that is extended quite often, having to constantly re-type all these properties just to pass them to super each time seems inefficient. I am likely missing some common way of preventing this. Any ideas how to make this more efficient? Perhaps by somehow "inheriting" the parent class's constructor parameters?
Here's a code example, and, as you can see, in Programmer
's constructor, I have to re-type name
, age
, and height
again just to pass it to super
:
class Person {
name: string;
age: number;
height: number;
constructor(name: string, age: number, height: number) {
this.name = name;
this.age = age;
this.height = height;
}
}
class Programmer extends Person {
languages: string[];
constructor(name: string, age: number, height: number, languages: string[]) {
super(name, age, height);
this.languages = languages;
}
}
You can't inherit, but you can refer to the parameter using ContructorParameters
and you can spread them back in your derived constructor, as long as you don't mind adding any new parameters at the front:
class Person {
name: string;
age: number;
height: number;
constructor(name: string, age: number, height: number) {
this.name = name;
this.age = age;
this.height = height;
}
}
class Programmer extends Person {
languages: string[];
constructor(languages: string[], ...p: ConstructorParameters<typeof Person>) {
super(...p);
this.languages = languages;
}
}
new Programmer(["A"], "", 1, 1) // Since 3.4 you will get actual parameter names in intelisense not just ...p
Not sure it's the best design though, and if you have a lot of parameters you might be better off defining an interface and passing that in instead. Or using some sort of mapped type to extract relevant fields.