6

I understand that, in TypeScript, one can:

Is it possible to combine these two behaviors? That is to say, is it possible to declare a base class which uses parameter properties, and then inherit from it in a derived class which also uses parameter properties? Does the derived class need to re-declare them, pass them into the superclass constructor call, etc.?

This is kinda confusing, and I can't figure out from the documentation whether this is intended to be possible, or -- if so -- how.

Thanks in advance if anyone has any insights into this.

1 Answer 1

12

You can combine the two, but from the point of the inheriting class the fields declared as constructor arguments will be regular fields and constructor arguments:

class Base {
    constructor(public field: string) { // base class declares the field in constructor arguments

    }
}

class Derived extends Base{
    constructor(public newField: string, // derived class can add fields
        field: string // no need to redeclare the base field
    ) {
        super(field); // we pass it to super as we would any other parameter
    }
}

Note

You can redeclare the field in the constructor argument but it will have to obey the rules for re-declaring fields (compatible types and visibility modifiers)

So this works:

class Base {
    constructor(public field: string) {

    }
}

class Derived extends Base{
    constructor(public field: string) { //Works, same modifier, same type, no harm from redeclration
        super(field);
    }
}

But this will not work :

class Base {
    // private field
    constructor(private field: string) {

    }
}

class Derived extends Base{
    constructor(private field: string) { //We can't redeclare a provate field
        super(field);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the clarification!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.