Skip to content

Overriding property type leads to possible incorrect value assignment. #36504

Closed
@bogdan

Description

@bogdan

TypeScript Version: 3.5.3

Search Terms:

property inheritance type override

Code

class A {
  params: {} = {}

  resetParams() {
    this.params = {};
  }
}

class B extends A {
  params: {b: number} = {b: 1};
}

const b = new B()
b.params // => {b: 1};
b.resetParams();
b.params // => {};

Expected behavior:

A type of params is strictly checked for incorrect assignment.
I do not see any solution to this myself other than disallow to override property type.
We can search how such cases are handled in other statically typed language like Java.

Actual behavior:

Typescript allows incorrect value assignment without any error.

Playground Link:
https://www.typescriptlang.org/play/?ssl=14&ssc=1&pln=15&pc=1#code/MYGwhgzhAECC0G8CwAoa0AOYBOYC2EAXIgL7QC8pqq62AphHQC4AKO+EAFAJSI3rQmACwCWEAHRZcBCqQDc-EqiUpUoSDABC0OgA8mdAHYATGPGRpM7AsQQAjYoYCueO3WxlK94gEYSClBU1AHtDCCZoO1lDOgB3aE0eELDgkDpxEGCAc047SWsIbgC8+kZWAp4A4FCIVPTMnLypDiLUIA

Related Issues:

In this issue, there is an example where typescript tracks a possibility of property type being override and rejects to compile: #35466

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions