TypeScript handles missing values with null and undefined. Enabling strictNullChecks forces developers to explicitly check for missing data using modern operators like optional chaining (?.) and nullish coalescing (??).
?. (Optional Chaining): Accesses nested properties safely without throwing a runtime TypeError.?? (Nullish Coalescing): Provides a fallback value only when the expression evaluates to null or undefined.! (Non-Null Assertion): Asserts to the compiler that a value is non-null (bypassing compile-time check).interface UserProfile {
id: string;
name: string;
contact?: {
phone?: string;
secondaryEmail?: string;
};
}
function printUserContact(user: UserProfile): void {
// Optional chaining safely returns undefined if contact is missing
const phone = user.contact?.phone;
// Nullish coalescing provides fallback only for null/undefined
const displayPhone = phone ?? "No phone provided";
console.log(`User ${user.name}: ${displayPhone}`);
}
const user1: UserProfile = { id: "1", name: "Alice" };
const user2: UserProfile = { id: "2", name: "Bob", contact: { phone: "+1-555-0199" } };
printUserContact(user1);
printUserContact(user2);
// Non-Null Assertion Operator (!)
function initializeElement(): void {
const container = document.getElementById("main-container")!; // Assert non-null
container.innerHTML = "<p>App initialized</p>";
}
?? Instead of || for Fallbacks: || treats empty string "" and 0 as falsy, whereas ?? only checks for null or undefined.!: Overusing ! bypasses type safety and can cause runtime crash if the element is actually null.strictNullChecks: Keep strictNullChecks: true inside tsconfig.json.Write a line of code using optional chaining user?.address?.city to access a deeply nested city property safely.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With