We can tell TypeScript that a value is not null with the post-fix operator !
. By adding the !
at the end of a function, we are saying "this function does not return null here", even if it normally could at other times.
For example:
// No post-fix !
const countryDropdown = document.querySelector('select#country');
// countryDropdown is Element | null
// With post-fix !
const yearDropdown = document.querySelector('select#year')!;
// yearDropdown is Element
In the example above, if we know for certain that <select id="year">
exists in the DOM, then by using the non-null assertion operator !
TypeScript knows that yearDropdown
is an Element
. This means we can avoid having to do null type checking before interacting with the yearDropdown
variable.