# Control Flow & Type Guards

> How TypeScript reads your if/else statements to narrow types.

Subject: TypeScript | Lesson 14 of 54 | 4 min read
Interactive lesson: https://codewithanimation.in/typescript/control-flow-type-guards
Previous: [The keyof Operator](https://codewithanimation.in/typescript/keyof-operator.md) | Next: [Type Predicates (is)](https://codewithanimation.in/typescript/type-predicates.md)

## Watching your code execute

When you have a Union Type like `string | number`, TypeScript is pessimistic: it won't let you use string methods or number methods because it doesn't know which one it is.

However, TypeScript's compiler is smart enough to read your control flow (`if`, `else`, `switch`, `return`). If you write standard JavaScript code to check the type, TypeScript updates its understanding of the variable inside that specific block.

## Type Narrowing

This process is called 'Type Narrowing'. A 'Type Guard' is just a standard JavaScript expression (like `typeof x === "string"`) that TypeScript recognizes as a way to narrow a type.

This allows you to write perfectly natural JavaScript code while getting strict type safety.

## Using typeof as a Type Guard

```typescript
function printId(id: string | number) {
  // Error: Property 'toUpperCase' does not exist on type 'number'
  // id.toUpperCase();

  if (typeof id === "string") {
    // TypeScript now knows 'id' is a string here!
    console.log(id.toUpperCase());
  } else {
    // TypeScript knows 'id' MUST be a number here!
    console.log(id.toFixed(2));
  }
}
```

## Common mistake: The extraction problem

A common frustration occurs when you try to clean up your code by extracting the Type Guard into a helper function:

```typescript
const isString = (val: any) => typeof val === "string";

if (isString(id)) {
  id.toUpperCase(); // Error! TS lost the type narrowing.
}
```

Because `isString` just returns a `boolean`, TypeScript doesn't know that the boolean specifically means 'the argument was a string'. (We fix this with Type Predicates in the next concept).

## Tip: The 'in' operator

For narrowing unions of objects, the JavaScript `in` operator is an excellent built-in type guard.

`if ("bark" in animal) { animal.bark(); }` tells TypeScript that the object has a bark method.

## Try it: Try it

Select a runtime value and watch how TypeScript narrows the `string | number` union based on the `if/else` execution path.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/typescript/control-flow-type-guards

## Check yourself

### Question 1

What is a 'Type Guard' in TypeScript?

- A. A special TypeScript keyword that locks a variable's type at runtime.
- B. A standard JavaScript expression (like typeof or instanceof) that TypeScript recognizes to narrow types.
- C. A decorator that prevents a variable from being null.

Correct answer: B

TypeScript doesn't invent new syntax for type guards; it just intelligently analyzes standard JavaScript control flow.

- Why not A: Type guards are usually just standard JavaScript code.
- Why not C: Not a decorator.

## Remember this

- TypeScript reads your `if/else` control flow to narrow types.
- A Type Guard is a JS expression that narrows a TS type.
- `typeof val === 'string'` narrows a union down to a string.
- Extracting a type guard to a normal function breaks the narrowing.
