Jerald
Jerald

Reputation: 4048

TSLint rules for checking undefined and NULL class properties

In my web applications when I define a class property which must contain some data type I always specify this data type. But application gets data asynchronously, so actually the property has undefined value and then it has real data:

class SomeClass {
    a: ISomeData;

    constructor() {
        getDataAsync().then((res: ISomeData) => this.a = res);
    }
}

I think that a: ISomeData is incorrect. It must be a: ISomeData | undefined. (It would be correct if this.a = someData were set synchronously in constructor) Is there tslint rules for checking that class propertise does not have data and must have undefined type?

Upvotes: 3

Views: 3150

Answers (1)

Daniel
Daniel

Reputation: 11182

By default any type you assign can take the values undefined and null along with any type declarations you have made.

In your TypeScript config file (tsconfig.json) you can set the StrictNullChecks compiler option to true.

{
  "compilerOptions": {
    "strictNullChecks": true
  }
}

From TypeScript docs on Compiler Options:

In strict null checking mode, the null and undefined values are not in the domain of every type and are only assignable to themselves and any (the one exception being that undefined is also assignable to void).

When you do that, a variable typed as ISomeData can only contain that type.

If you want undefined/null values, you'd have to type it like

a: ISomeData | undefined | null;

Upvotes: 6

Related Questions