This is a more theoretical question regarding what TypeScript does under the hood.
As specified in this question and based on personal experience, there are two ways of handling constructor parameter properties when inheriting from a class.
Passing existing fields
class Base {
constructor(public field: string) {}
}
class Derived extends Base {
constructor(field: string) {
super(field);
}
}
Redeclaring existing fields
class Base {
constructor(public field: string) {}
}
class Derived extends Base {
constructor(public field: string) {
super(field);
}
}
As per the linked question and answer, there are limitations to how the field can be redeclared, but those are clear to me.
My questions are the following:
- Does the second approach define two fields on the class, where the first is shadowed by the second? Would
this.fieldandsuper.fieldevaluate to different attributes of the class? - Similarly to the previous question, does the second approach behave differently with methods defined in the
BaseandDerivedclasses?
Ultimately it boils down to the question: Are these approaches functionaly identical, or do they behave differently in some edge-cases?
Based on personal experience, the two approaches seem to do the same thing.
I would personaly go with the first approach, as I feel like "nothing can go wrong" and that there will be no hidden pitfalls with this approach, but I would like to understand this better, so that I don't base my programming decisions on vague feelings.
Thank you for your answers.