Under --strictNullChecks, class properties that are left uninitialized are problematic:
class Foo {
someprop: string;
}
var a = new Foo();
a.someprop === undefined; // true
I suggest we have a rule that checks that properties are initialized, either inline or in the constructor.
As of today, the equivalent compiler feature is marked wontfix, see https://github.com/Microsoft/TypeScript/issues/8476.
@nippur72 cool, that sounds like a valid rule to exist in core. Maybe something like "no-uninitialized-member".
How should this rule work for patterns like this?
class Foo {
someprop: string;
constructor() {
this.init('self');
}
init(s: string) {
this.someprop = s;
}
}
Ideally it should walk all paths in the constructor and check for this at the end of the constructor.
But still there will be cases where the rule is going to fail, e.g.:
class Foo {
someprop: string;
constructor() {
let a = this;
a.someprop = "42";
}
}
Try this. At the moment it does not care about delegating initializers and/or base classes. Microsoft/TypeScript#8476
@helmutschneider Have you extended this rule at all since October? I would love to see something like this in tslint to make strictNullChecks useful.
@abierbaum I have not, no. It needs to be updated for tslint 4.0 but I believe that's a small change. Even if it were to be merged I'm not sure I would have the time to maintain it in the future. Feel free to use the code as you like - I give you my full consent.
@abierbaum I just updated the gist for tslint 4.0.
See https://github.com/alhugone/tslint-strict-null-checks for a potential way to implement this.
Typescript has implemented this in version 2.7. https://blogs.msdn.microsoft.com/typescript/2018/01/31/announcing-typescript-2-7/
Closing in favor of the compiler feature
Most helpful comment
See https://github.com/alhugone/tslint-strict-null-checks for a potential way to implement this.