Close

TypeScript - Non-Null Assertion Operator !

[Last Updated: Oct 27, 2018]

The post-fix expression operator ! may be used to assert that its operand cannot be null or undefined during runtime.

This operator can be used where the compiler is unable to check that a variable cannot be null/undefined.

Example

In following example, the splitInHalf() method makes sure via checkString(str) call that str variable cannot be null, before it is used:

function splitInHalf(str: string | null) {
    let checkString = function () {
        if (str == null || str == undefined) {
            str = "test";
        }
    }
    checkString();
    return str.substring(0, str.length / 2);
}

let s = splitInHalf("bean");
console.log(s);

Output

be

But if we compile above code with --strictNullChecks then:

function splitInHalf(str: string | null) {
    let checkString = function () {
        if (str == null || str == undefined) {
            str = "test";
        }
    }
    checkString();
    return str.substring(0, str.length / 2);
}

let s = splitInHalf("bean");
console.log(s);
8:29 - error TS2531: Object is possibly 'null'.
8     return str.substring(0, str.length / 2);
              ^

To tell TypeScript that the variable 'str' cannot be null, we can use ! operator (non-null assertion operator).

Running following with --strictNullChecks flag:

function splitInHalf(str: string | null) {
    let checkString = function () {
        if (str == null || str == undefined) {
            str = "test";
        }
    }
    checkString();
    return str!.substring(0, str!.length / 2);
}

let s = splitInHalf("bean");
console.log(s);

Output

be

Example Project

Dependencies and Technologies Used:

  • TypeScript 3.1.3
TypeScript - Non-Null Assertion Operator Select All Download
  • typescript-non-null-assertion-operator
    • non-null-assertion-fix.ts

    See Also