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); Outputbe
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); Outputbe
Example ProjectDependencies and Technologies Used: |