Conditions, loops and narrowing
if, switch, for…of and while, and how a check narrows a union type.
Runs in Zerethon IDE · TypeScript 7
Official TypeScript documentation ↗
main.ts
function describe(value: number | string | string[]): string {
if (typeof value === 'number') {
return `number ${value.toFixed(1)}`; // value: number here
}
if (Array.isArray(value)) {
return `list of ${value.length}`;
}
return `text ${value.toUpperCase()}`;
}
for (const v of [3, 'hi', ['a', 'b']]) {
console.log(describe(v));
}
type Shape = { kind: 'circle'; r: number } | { kind: 'square'; side: number };
function area(s: Shape): number {
switch (s.kind) {
case 'circle':
return Math.round(Math.PI * s.r ** 2);
case 'square':
return s.side ** 2;
}
}
console.log(area({ kind: 'circle', r: 2 }), area({ kind: 'square', side: 3 }));
let i = 0;
while (i < 2) console.log('i =', i++);
Output
number 3.0 text HI list of 2 13 9 i = 0 i = 1
Tip: A shared kind field (a discriminated union) lets switch know which shape it has, and the compiler checks that every case returns.