Skip to content

Default class parameter values stomp value set in constructor when subclassing #15648

Closed
@btraut

Description

@btraut

TypeScript currently sets default class param values at the end of the constructor if that constructor doesn't already set a value. In fact, it's smart enough that if the constructor calls another function that sets the value, the default won't be set. Unfortunately, I've found a scenario involving inheritance where I set a value during construction, and then the default class param value stomps it:

  1. Child class constructor is called.
  2. Child class calls super's constructor.
  3. Super class constructor calls a method which the child class overrides, thus calling back into child class' code.
  4. This child method sets a parameter value.
  5. -- constructor code finishes --
  6. TypeScript erroneously sets the default for the child's parameter, stomping on the value set in 4.

I'm not fully aware of the implications, but it seems to me as if default class param values should be set every time (instead of conditionally), and they should be set at the beginning of the constructor before any constructor code or calls to super execute. Either this, or the check to set the default parameter needs to be smarter to detect this case.

TypeScript Version: 2.2.1 / nightly (2.2.0-dev.201xxxxx)

Code

class Foo {
  constructor(myVal: number) {
    this._setMyVal(myVal);
  }

  protected _setMyVal(myVal: number) {
    // The subclass overrides this method.
  }
}

class Bar extends Foo {
  private _myVal = 123;

  constructor(myVal: number) {
    super(myVal);
  }

  protected _setMyVal(myVal: number) {
    this._myVal = myVal;
  }

  public log() {
    console.log(this._myVal);
  }
}

const test = new Bar(9);
test.log(); // 123

Expected behavior:

Purely from how I read the code above, given how other languages work, I would expect the final value of _myVal to be 9. Regardless of its default, I set a value during construction and that value shouldn't get reset later.

Actual behavior:

As per the example, TypeScript compiles this to execute this._myVal = 123; after all constructor code is finished, thus stomping any values set during construction.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions