Note
Non-null Assertion Operator in TypeScript
What the postfix `!` means in TypeScript and when it helps the compiler trust a value.
Have you seen something like node!.parent and wondered what the postfix ! is doing in TypeScript code?
That is the non-null assertion operator, introduced in TypeScript 2.0. As the documentation notes:
A new
!post-fix expression operator may be used to assert that its operand is non-null and non-undefined in contexts where the type checker is unable to conclude that fact.
Now let us look at a simple use case. Suppose we have document.getElementById('post'); TypeScript cannot determine whether the element will be present in the DOM. In cases like that, we can tell the type checker that the element is present by using the postfix !.
let postEl: HTMLElement = document.getElementById('post');
const post = new Blog(postEl, {
mood: '😊',
});
That will produce an error because document.getElementById() returns HTMLElement | null.
By changing the first line like this:
const postEl: HTMLElement = document.getElementById('post')!;
the error goes away and the code compiles.
The important detail is that the ! only affects the type checker. It is removed from the emitted JavaScript.
Happy coding.