Nullish Values & !
Handling nothingness and the danger of the non-null assertion.
Strict Null Checks
Historically, JavaScript has two ways to represent 'nothing': null (intentional absence) and undefined (uninitialized).
By default, TypeScript forces you to explicitly handle these values if your tsconfig.json has strictNullChecks: true (which all modern projects should). If a variable can be a string or null, you cannot call string methods on it until you prove it is not null.
The Billion Dollar Mistake
Tony Hoare famously called the invention of the null reference his 'billion-dollar mistake' because it caused decades of unhandled runtime crashes.
TypeScript prevents this by forcing you to write if (myVar) before accessing properties on potentially null variables.
The ! Operator
Sometimes, you know a value isn't null, but TypeScript doesn't. For example, querying the DOM for an element you know exists.
You can append ! to a variable (the Non-Null Assertion Operator) to tell the compiler 'Trust me, this isn't null'.
typescript
// returns HTMLElement | null
const el = document.getElementById("app");
// Error: Object is possibly 'null'.
el.innerHTML = "hi";
// We silence the compiler with '!'
el!.innerHTML = "hi";
Try it
Watch how appending ! instantly removes a null-check compiler error, but leaves the runtime completely unprotected.
! Non-Null Assertion Operator tells the compiler to completely ignore the possibility that btn is null.Danger!
The ! is erased during compilation. If the element doesn't exist, the browser will crash at runtime with TypeError: Cannot read properties of null.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
strictNullChecksforces you to handlenullandundefined.- The
!operator tells the compiler to ignore potential nulls. - Using
!is dangerous because it provides zero runtime protection. - Prefer Optional Chaining (
?.) or explicitifchecks.
Done with this concept?
Mark it complete to track your progress. No login needed.