What is a type guard in TypeScript?

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.