Conditions & Switches
TypeScript conditional logic with type narrowing and discriminated unions.
if / else
const value: number = 10;
if (value > 10) {
console.log("big");
} else if (value <= 10 && value !== 0) {
console.log("medium");
} else {
console.log("small");
}
Ternary
const result = value > 1 ? "amazing" : "not amazing";
Nullish coalescing
const name = input ?? "default"; // null or undefined only
const label = input || "fallback"; // any falsy value
Type Narrowing
TypeScript narrows types inside conditional blocks:
function process(value: string | number) {
if (typeof value === "string") {
// value: string
console.log(value.toUpperCase());
} else {
// value: number
console.log(value.toFixed(2));
}
}
instanceof
if (error instanceof TypeError) { ... }
in operator
if ("name" in obj) {
console.log(obj.name); // narrowed
}
Discriminated Unions
type Result =
| { status: "ok"; data: string }
| { status: "error"; message: string };
function handle(result: Result) {
switch (result.status) {
case "ok":
console.log(result.data); // narrowed to ok
break;
case "error":
console.log(result.message); // narrowed to error
break;
}
}
switch
switch (command) {
case "start":
start();
break;
case "stop":
case "quit":
stop();
break;
default:
unknown();
}
Next: Collections & Loops