# Type Guards & Narrowing

> What are type guards in TypeScript, and how does the compiler narrow a union type based on runtime checks like typeof, instanceof and in?

Canonical: https://www.internhack.in/learn/interview/typescript-interview/ts-type-guards-narrowing
Last updated: 2026-11-28

Difficulty: Intermediate

## Question

What are type guards in TypeScript, and how does the compiler narrow a union type based on runtime checks like \`typeof\`, \`instanceof\` and \`in\`?

## Answer

A type guard is a runtime check that TypeScript understands well enough to narrow a variable's type inside the guarded block. After `if (typeof id === "string")`, the compiler treats `id` as `string` in that branch and as the remaining union members in the `else`. This process is called control flow narrowing, and it is how you work safely with unions without casting.

### The built-in guards

- `typeof x === "string" | "number" | "boolean" | "bigint" | "symbol" | "undefined" | "function" | "object"` for primitives. Remember `typeof null === "object"`, so check `x !== null` too.
- `x instanceof Date` for class instances; it checks the prototype chain.
- `"refund" in event` narrows unions of object types by property presence.
- Equality: `x === null`, `x == null` (covers `undefined` too), or comparing a literal discriminant like `shape.kind === "circle"`.
- Truthiness: `if (user)` removes `null` and `undefined`, but also `0` and `""`, which bites with amounts in paise or empty strings.
- `Array.isArray(x)` narrows to an array type.

### How control flow analysis works

The compiler tracks every assignment and condition along each code path. Early returns narrow everything after them, `switch` cases narrow per branch, and `&&` and `||` narrow their right-hand sides. Narrowing resets when a variable is reassigned, and it does not survive into callbacks for `let` variables because the callback could run later after reassignment. Using `const` or copying to a local fixes that.

### Custom type guards (type predicates)

When the check is too complex for the built-ins, write a function returning `value is Type`. TypeScript trusts this predicate completely, so a buggy guard is as dangerous as a wrong cast. Since TypeScript 5.5 the compiler can infer simple predicates automatically, so `arr.filter(x => x !== undefined)` now returns `T[]` instead of `(T | undefined)[]`.

Assertion functions (`asserts value is Type`) are the throwing variant: after calling `assertIsUser(x)`, the rest of the scope sees `x` as `User`. They pair well with validation libraries.

### Where guards show up in practice

- Handling webhook payloads where `event.type` decides the shape.
- Narrowing `unknown` from `JSON.parse` or a `catch (err)` clause with `err instanceof Error`.
- Filtering arrays of mixed results, such as `Promise.allSettled` outcomes by `status === "fulfilled"`.

### Common mistakes

- Using a truthiness check on numbers and strings that may legitimately be `0` or `""`.
- Writing a predicate that checks one field and claims the whole type.
- Expecting `instanceof` to work on interfaces or type aliases; they do not exist at runtime.

**Narrowing string | number | null. Each check removes possibilities from the union along that code path.**

1. **id: string | number | null**: Declared union type.
2. **if (id === null) return**: Early return removes null.
3. **typeof id === 'string'**: True branch sees string.
4. **else branch**: Only number remains.

## Code examples

### Built-in narrowing

```
type Amount = number | string | null;

function toPaise(amount: Amount): number {
  if (amount === null) return 0;        // null removed below
  if (typeof amount === "string") {
    return Math.round(parseFloat(amount) * 100); // amount: string
  }
  return Math.round(amount * 100);      // amount: number
}

class ApiError extends Error { constructor(public status: number) { super(); } }

function handle(err: unknown) {
  if (err instanceof ApiError) return err.status; // ApiError
  if (err instanceof Error) return err.message;   // Error
  return String(err);                              // unknown
}
```

Equality, typeof and instanceof checks each narrow the union along their branch. In catch blocks errors are unknown by default under strict, so instanceof is the standard narrowing tool.

### in operator and custom predicates

```
interface CardPayment { cardLast4: string }
interface UpiPayment { vpa: string }
type Payment = CardPayment | UpiPayment;

function describe(p: Payment) {
  if ("vpa" in p) return `UPI ${p.vpa}`;   // UpiPayment
  return `Card ending ${p.cardLast4}`;      // CardPayment
}

// Custom type guard with a type predicate
function isUpi(p: Payment): p is UpiPayment {
  return typeof (p as UpiPayment).vpa === "string";
}

const payments: Payment[] = [{ vpa: "asha@okaxis" }, { cardLast4: "4242" }];
const upiOnly = payments.filter(isUpi); // UpiPayment[]
```

The in operator narrows object unions by property presence. A predicate function lets you reuse a check, and filter uses it to narrow the array type.

### Assertion functions and inferred predicates (TS 5.5+)

```
function assertIsString(v: unknown, name: string): asserts v is string {
  if (typeof v !== "string") throw new TypeError(`${name} must be a string`);
}

function readEnv(key: string): string {
  const value = process.env[key]; // string | undefined
  assertIsString(value, key);
  return value;                   // string from here on
}

// TypeScript 5.5+ infers the predicate for simple arrow functions
const ids = ["a", undefined, "b"].filter((x) => x !== undefined);
//    ^? string[]  (was (string | undefined)[] before 5.5)
```

An asserts signature narrows everything after the call or throws. From TypeScript 5.5 the compiler infers type predicates for simple filter callbacks.

## Key points

- Narrowing is compile-time bookkeeping driven by real runtime checks.
- \`typeof null\` is "object"; check null explicitly.
- Custom predicates (\`x is T\`) are trusted blindly, so keep them accurate.
- \`asserts x is T\` narrows the rest of the scope or throws.
- TypeScript 5.5 infers type predicates for simple callbacks like filter.

## Common follow-up questions

- Why does narrowing sometimes get lost inside a callback?
- What is the difference between a type predicate and an assertion function?
- How do discriminated unions make narrowing easier?
- How would you narrow an \`unknown\` value from JSON.parse safely?

## Interview tips

- List the guards (typeof, instanceof, in, equality, truthiness, predicates) and give a one-line example of each.
- Mention the truthiness trap with 0 and empty strings; it shows you have debugged real code.
- Say that predicates are trusted, so a wrong one is effectively an unsafe cast.

## Concepts covered

Type Guards, Control Flow Narrowing, Type Predicates, instanceof, in Operator, Assertion Functions

Previous: [Generics & Utility Types](https://www.internhack.in/learn/interview/typescript-interview/ts-generics-interview) · Next: [Why TypeScript? JS vs TS](https://www.internhack.in/learn/interview/typescript-interview/ts-why-typescript) · [All of TypeScript Interview](https://www.internhack.in/learn/interview/typescript-interview)

## More TypeScript Interview questions

- [Basic Types & Annotations](https://www.internhack.in/learn/interview/typescript-interview/ts-basic-types)
- [Arrays, Tuples & Enums](https://www.internhack.in/learn/interview/typescript-interview/ts-arrays-tuples-enums)
- [Functions & Overloads](https://www.internhack.in/learn/interview/typescript-interview/ts-functions-overloads)
- [Object Types & Optional Props](https://www.internhack.in/learn/interview/typescript-interview/ts-object-types)
- [Union & Intersection Types](https://www.internhack.in/learn/interview/typescript-interview/ts-union-intersection)
- [Literal Types & const Assertions](https://www.internhack.in/learn/interview/typescript-interview/ts-literal-const)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [TypeScript Interview](https://www.internhack.in/learn/interview/typescript-interview)
