Search code examples
typescriptnullassertionstrict

strictNullChecks: true in my tsconfig.json vs. not null assertion operator usage


The strictNullChecks: true in the tsconfig.json!

Is it allowed to use a not null assertion operator if we are sure the object is not null and undefined?

In the following example, where the type checker is unable to conclude that fact is non-null and non-undefined.

        if (this.objArray[ix].arrayItem) {
            this.objArray[ix].arrayItem!.prop1 = prop1Value;
            this.objArray[ix].arrayItem!.prop2 = prop2Value;
            this.objArray[ix].arrayItem!.prop3 = prop3Value;
        }

I checked the official doc, https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html#non-null-assertion-operator but I do not found similar example.

What do you think about that? What is the best practice?


Solution

  • The solution for your problem is an intermediate variable.

    const item = this.objArray[ix].arrayItem;
    if (item) {
        item.prop1 = prop1Value;
        item.prop2 = prop2Value;
        item.prop3 = prop3Value;
    }