liveBook · Manning

Type guard

As explained in Acing the Frontend Interview

A type guard is a runtime check or predicate that narrows a value to a more specific TypeScript type.

A type guard is a runtime check or predicate that narrows a value to a more specific TypeScript type. It is especially useful when handling values whose type is unknown, such as API responses, user input, or parsed JSON. section 3.12 section 3.7

Using typeof to narrow unknown

let vUnknown: unknown = 10; if (typeof vUnknown === "number") { let text: string = vUnknown.toString(); } The typeof check narrows vUnknown before the value is used. Without narrowing, assigning it directly or calling a method is not permitted. section 3.7

Interview points to articulate:

  • Prefer unknown over any for uncertain values because unknown requires explicit checks, while any bypasses type checking and can cause runtime errors. section 3.7
  • For deeply nested or unpredictable external data, combine partial validation, critical-field assertions, utility types, or schema validation libraries. section 3.7

How Acing the Frontend Interview covers it

How deep it goes
Explains narrowing through typeof and contrasts unknown with any, but does not develop custom guard predicates.
Examples
Demonstrates typeof narrowing on an unknown number and contrasts safe access with direct assignment or method calls.
What it assumes
Assumes basic TypeScript types while reinforcing static typing, type safety, and explicit narrowing.
What you can do after
Apply explicit runtime checks to use unknown values safely and explain when broader validation strategies are needed.
How it connects
Connects type guards with static typing, unknown, any, runtime validation, and schema validation libraries.

Also explained in

Compare how 2 books explain type guard →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Acing the Frontend Interview. The section links point to the parts of the book it draws on.