Operators
Operators perform standard math, evaluations, and structural transformations in TypeScript. Let's look at its unique utility operators alongside traditional operators.
1. Arithmetic & Relational Operators
let x: number = 10;
let y: number = 3;
// Modulus remainder operation
let remainder = x % y; // 1
// Strict structural comparisons
console.log(x === 10); // true (checks value and type alignment)
console.log(x !== y); // true
2. Logical Operators
let clearSky: boolean = true;
let lowWind: boolean = false;
// Compound conditional checks
let safeLaunch: boolean = clearSky && !lowWind; // true
3. Advanced TypeScript-Specific Operators
a. Optional Chaining (?.)
Safely reads deeply nested object properties without manually verifying each parent layer's existence first:
type Profile = { address?: { city: string } };
let userProfile: Profile = {};
// Prevents runtime crashes; evaluates cleanly to undefined if missing
let missingCity = userProfile.address?.city;
b. Nullish Coalescing (??)
Returns its right-hand side operand when its left-hand side operand is null or undefined. Unlike fallback ||, it ignores falsey values like empty strings "" or numerical zero 0.
let dynamicLimit: number | null = null;
let workingLimit = dynamicLimit ?? 100; // Evaluates to 100
Finished reading? Mark this topic as complete.