../courses.php
TypeScript
TS106
3
Null And Undefined Still Bite
TypeScript helps expose missing values, but you still have to handle them.
Why are null and undefined dangerous?
Null and undefined are dangerous because they mean a value is missing, and using a missing value like a real object can crash or break the program.
Many JavaScript bugs come from missing values.
A user may not exist.
A property may be missing.
A function may return nothing.
TypeScript can warn you, but the code still needs a safe path.
Checking before using a missing value
type User = {
email: string;
};
let user: User | undefined = undefined;
if (user) {
console.log(user.email);
} else {
console.log("No user found.");
}
User | undefined means the value may be a User or may be missing.
The variable starts as undefined.
The if (user) check confirms a real user exists.
The email is used only after the check passes.
The else branch handles the missing-value case.
Missing data
Real applications often have absent values.
Unions
A union type can show that more than one kind of value is possible.
Checks
The code must check before using uncertain values.
Safety
Handling missing values prevents common runtime failures.
Using a value without checking
Checking first
if (user) {
console.log(user.email);
}
Ask ChatGPT: "Where can this TypeScript value be null or undefined, and how should I guard it?"
Create a type for a User.
Create a variable that can be User or undefined.
Check whether the user exists.
Use email only after the check.
Explain why missing values still matter.
Assuming a value always exists.
Ignoring undefined warnings.
Using optional chaining without understanding the missing case.
Pretending TypeScript removes all runtime problems.
Forgetting to write an else path.
Handle null and undefined safely in simple TypeScript code.
Login - Jit4All
Login
Welcome back to Jit4All