1

I expected the following typescript code might cause a compile error, as the property in the derived class has the same name as the property in the base class, but with a different type. However, this code compiles without issues and Derived.property shadows Base.property, causing subtle bugs. Is it possible to prevent this kind of code, either through the compiler or a linter?

class Base {
  protected property: {};
  constructor(property: {}) {
    this.property = property;
  }
}

class Derived extends Base {
  property = 1;
}
simonhorlick
  • 107
  • 4
  • This related [answer](https://stackoverflow.com/questions/58338400/class-attribute-type-pass-by-extends-in-typescript/58344423#58344423) might also be of interest. – ford04 Nov 11 '19 at 07:12

1 Answers1

1

Actually this is expected when setting empty object ={}. As this can be extended to number, string etc. .

What you actually want is to restrict its type

type Options = {
  option1?: boolean
}
class Base {
  protected property: Options;
  constructor(property: {}) {
    this.property = property;
  }
}

class Derived extends Base {
  property = 1; // does not work (2416)
}
Estradiaz
  • 3,483
  • 1
  • 11
  • 22