How are null and undefined treated in TypeScript when strictNullChecks is on?
With strictNullChecks, null and undefined are their own types and are not assignable to string, number or objects unless you say so in a union such as string | null. The compiler then forces you to check before using the value.
Explain it simply
Picture a UPI app asking for a phone number. Either you typed one, or the field is empty. If the code pretends the field always has a number, it crashes the moment someone leaves it blank.
Without strictNullChecks, TypeScript lets null and undefined slip into every type, so that crash goes unnoticed. With it on (part of strict), you must write the possibility into the type, and TypeScript refuses .length on something that might be missing until you check.
Convention: undefined usually means "never set" (an optional field), null means "deliberately empty".
Example
let phone: string | null = null;
// phone.length; // Error: 'phone' is possibly 'null'
if (phone !== null) {
console.log(phone.length); // OK: narrowed to string
}
interface User { name: string; email?: string } // email: string | undefined
const u: User = { name: "Asha" };
const domain = u.email?.split("@")[1] ?? "unknown"; // optional chaining + default
// let age: number = undefined; // Error under strictNullChecksWhat to say in the interview
"Under strictNullChecks, null and undefined are separate types, so a value that can be missing must be typed as a union. TypeScript then makes me narrow it with a check, optional chaining or a nullish default before I use it. It catches the classic 'cannot read property of undefined' bug at compile time."
Common mistakes
- Using the non-null assertion
!to silence the error instead of handling the empty case.