const el = document.getElementById("root")!; // HTMLElement
const user = users.find((u) => u.id === id)!; // User
The ! after a value removes null and undefined from its type. It is risky because it does no check at runtime. Safer options are an explicit check, ?. with ??, or an assertion function.
! tells the compiler "trust me, this is defined". But it adds no runtime check. If you are wrong, the program crashes later with a "cannot read properties of undefined" error. The crash is often far from the line where you made the assumption.
It also hides problems when code changes. If someone renames the element id, the ! still compiles.
Safer alternatives:
- An explicit check with an early return, or a thrown error with a clear message.
- Optional chaining
?.with a fallback value from??. - A small assertion function.
! is acceptable when you can prove the value exists and a check would only add noise. But remember that each ! is a spot the compiler no longer protects.
!removesnullandundefinedfrom the type only, not at runtime.- There is no runtime check, so a wrong assumption crashes later.
- Code with
!keeps compiling even after a change breaks the assumption. - Prefer explicit checks,
?.with??, or assertion functions.
Read more