TypeScript if, else and switch: Decisions for Beginners
November 6, 2026
Welcome to episode 6 of TypeScript from Zero, a series for complete beginners (no JavaScript needed). Welcome back to TypeScript from zero! Today: decisions. A program can choose what to do, depending on a condition. A new file called decisions.ts. Every code block below is the code from the video, ready to copy; run each file to see the output.
- All episodes are in the TypeScript from Zero playlist.
- Versions used: Node.js 26.13.0, npm 11.20.0, TypeScript 7.0.2.
Setup
We start in the terminal and open the project in VS Code:
$ touch decisions.ts1. if
The if statement runs its block only when the condition is true. If the temperature is above thirty, print hot. Else if it is above twenty, print warm. Else, print cold. Only the first block that matches runs. Twenty five degrees: warm.
const temperature = 25;
if (temperature > 30) {
console.log("Hot");
} else if (temperature > 20) {
console.log("Warm");
} else {
console.log("Cold");
}$ node decisions.ts2. Ternary
For a simple choice there is a short form, the ternary operator. A condition, a question mark, the value if true, a colon, and the value if false. It gives a value, so we can store it in a constant.
const label = temperature > 20 ? "warm" : "cold";
console.log(label);$ node decisions.ts3. switch
When we compare one value with many exact options, switch is clearer. Each case is one option. Break ends the case, and without it Node would continue into the next one. Default runs when nothing matches. Day three has no case, so default runs.
const day: number = 3;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
default:
console.log("Another day");
}$ node decisions.ts4. Wrong case
Now we add a case for day three, but we write it as text, three in quotes. Node runs the program and nothing breaks. Still another day. A silent mistake.
$ node decisions.ts5. tsc
tsc finds it: type string is not comparable to type number. We switch on a number, so a case with text can never match.
$ npx tsc --noEmit decisions.ts6. Fix
We write three as a number. tsc is quiet, and now the Wednesday case runs.
$ npx tsc --noEmit decisions.ts$ node decisions.tsRecap
Today: if, else if and else, the ternary operator for a quick choice, and switch for exact options, with break and default. Next episode: loops.