Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 96 ยท Basic Types

Control Flow and Loops

Learn if, switch, for, while, for...of, for...in and forEach in TypeScript, how loop variables are typed, why for...in keys are strings, labels and exhaustive switches.

Control flow decides which lines of code run, and how many times. The statements are the ones from JavaScript: if, switch, for, while. TypeScript's contribution is that it follows the flow with you. After an if check, the compiler knows more about your variables, and loop variables get the right types without annotations.

This lesson covers branching, every kind of loop, what type each loop variable gets, and the pitfalls that surprise newcomers (the biggest one: for...in gives you strings).

if, else and narrowing

An if statement runs a block when its condition is truthy. Inside the block, TypeScript narrows the type according to the condition:

TypeScript if / else if narrows the type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Each branch sees a smaller type. This is control flow analysis, and it is the foundation of narrowing. Early return statements work the same way: after if (x === undefined) return;, the rest of the function knows x is defined.

switch statements

switch compares one value against several case values using strict equality. With a union of literals, TypeScript can check that you handled every case.

TypeScript An exhaustive switch with never

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

If you later add { kind: 'hexagon' ... } to Shape and forget the case, the assignment to never fails to compile. The pattern is explained in Discriminated Unions.

Two switch gotchas that TypeScript can help with. First, fallthrough: without break or return, execution continues into the next case. Turn on the compiler option noFallthroughCasesInSwitch (part of many strict presets) to get an error on accidental fallthrough. Second, case bodies share one scope, so wrap declarations in braces { } as the default branch above does.

The classic for loop

for (init; condition; update) is the loop to use when you need an index or a custom step.

TypeScript for and while loops

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

With the strict option noUncheckedIndexedAccess, scores[i] has the type number | undefined, because an index might be out of range. That option is not part of strict, but it is worth enabling. If you iterate with for...of (next section) you avoid the issue.

for...of: iterate over values

for...of walks any iterable: arrays, strings, Map, Set, generators. The loop variable gets the element type automatically.

TypeScript for...of and the types it infers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Use const for the loop variable unless you reassign it. A new binding is created for each iteration, so closures capture the right value. For arrays, for...of is usually the clearest choice. It also works with break and continue, unlike forEach.

for...in: iterate over keys (as strings)

for...in loops over the enumerable property names of an object. The key is always typed string, even when the object has specific keys:

TypeScript for...in gives strings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Why is the key a plain string? Because objects can have more properties at runtime than their declared type says (a subtype may add some), and for...in also walks inherited properties. TypeScript refuses to promise otherwise. Prefer Object.entries, Object.keys and for...of. Reserve for...in for situations where you really need it, and never use it on arrays.

forEach, map and other array methods

Array methods take callbacks and infer parameter types from the array:

TypeScript Callbacks get inferred parameter types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

forEach cannot be stopped with break, and returning from the callback only leaves that one call. It also does not wait for async callbacks. When you need early exit or await, use for...of. See Promises and Async.

break, continue and labels

break leaves the loop, and continue jumps to the next iteration. To leave an outer loop from an inner one, put a label in front of the loop:

TypeScript Labeled break and continue

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Labels are rarely needed. Often a helper function with an early return is cleaner, but a label is fine for a short search like this.

Typing loop variables yourself

You almost never annotate a loop variable, and in fact you cannot: for...of and for...in heads do not accept a type annotation. If the elements are typed too loosely, fix the iterable's type instead:

TypeScript
declare const list: unknown[];

// for (const item: string of list) {}      // error TS2483: The left-hand side of a 'for...of' statement cannot use a type annotation.
for (const item of list as string[]) {}     // assert the iterable instead

If the iterable is unknown, narrow it first with Array.isArray or a type guard rather than asserting.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In for (const key in obj), where obj: { a: number; b: number }, what is the type of key?

    for...in always produces strings, because an object can hold more keys at runtime than its type lists. Use Object.entries or assert key as keyof typeof obj.
  2. 2. Which loop lets you use break and await freely?

    for...of is a statement in your function, so break, continue, return and await work normally. Callbacks run in separate functions.
  3. 3. What is the purpose of const unreachable: never = shape; in the default branch of a switch?

    If every member was handled, shape is never there. If one is missing, the assignment fails to compile.
  4. 4. What does break outer; do?

    A label names a loop so that break and continue can target an outer one.
  5. 5. Which option adds | undefined to the type of scores[i]?

    noUncheckedIndexedAccess models that an index may be out of range.

Summary

  • if and switch narrow types inside each branch; an exhaustive switch with a never check catches missing cases.
  • Use for when you need an index, while for open-ended loops and for...of for values of any iterable.
  • for...in keys are string; prefer Object.entries and Object.keys, and never loop over arrays with it.
  • forEach, map, filter and reduce infer callback parameter types, but cannot break or await.
  • Labels let break and continue target an outer loop.
  • Loop variables are inferred, so you rarely annotate them.

Next: Objects