What is a type guard in TypeScript?

Why Interviewers Ask This

Interviewers use this question to quickly assess whether a candidate has the foundational knowledge required for TypeScript development. It reveals whether you understand the building blocks that more complex concepts rely on.

Answer

A type guard is an expression or function that narrows the type of a variable within a conditional block. Built-in type guards: typeof (checks primitive types), instanceof (checks class instances), in (checks property existence), truthiness checks. User-defined type guard: a function with a return type of parameterName is Type: function isString(value: unknown): value is string { return typeof value === "string"; }. After calling this guard in a condition, TypeScript knows the type within that block: if (isString(data)) { data.toUpperCase(); /* data is string here */ }. Assertion functions (TS 3.7): function assertIsString(val: unknown): asserts val is string { if (typeof val !== "string") throw new Error(); } — after calling this, the type is narrowed without an if block. Type guards are essential for working safely with unknown types, union types, and API responses.

Pro Tip

Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex TypeScript answers easy to follow.