Skip to content
This repository has been archived by the owner on Mar 25, 2021. It is now read-only.

Add a rule to check uninitialized class properties under strictNullChecks #1414

Closed
nippur72 opened this issue Jul 18, 2016 · 10 comments
Closed

Comments

@nippur72
Copy link

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 microsoft/TypeScript#8476.

@adidahiya
Copy link
Contributor

@nippur72 cool, that sounds like a valid rule to exist in core. Maybe something like "no-uninitialized-member".

@RyanCavanaugh
Copy link

How should this rule work for patterns like this?

class Foo {
  someprop: string;

  constructor() {
    this.init('self');
  }

  init(s: string) {
    this.someprop = s;
  }
}

@nippur72
Copy link
Author

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";
  }
}

@helmutschneider
Copy link

helmutschneider commented Oct 4, 2016

Try this. At the moment it does not care about delegating initializers and/or base classes. microsoft/TypeScript#8476

@abierbaum
Copy link
Contributor

@helmutschneider Have you extended this rule at all since October? I would love to see something like this in tslint to make strictNullChecks useful.

@helmutschneider
Copy link

@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.

@helmutschneider
Copy link

@abierbaum I just updated the gist for tslint 4.0.

@abierbaum
Copy link
Contributor

See https://github.com/alhugone/tslint-strict-null-checks for a potential way to implement this.

@dweber019
Copy link

Typescript has implemented this in version 2.7. https://blogs.msdn.microsoft.com/typescript/2018/01/31/announcing-typescript-2-7/

@adidahiya
Copy link
Contributor

Closing in favor of the compiler feature

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

7 participants