Back to all snippets
Library/TypeScript/Type Guards
typescriptintermediatetypesguardsutilities

How to implement Type Guards in Typescript

Custom type guards for runtime type checking

Quick Answer

A TypeScript type guard is a function with a `value is Type` return annotation that lets the compiler narrow the type inside an if-block after a runtime check.

Code Snippet

1function isString(value: unknown): value is string {
2  return typeof value === 'string';
3}
4
5function isNumber(value: unknown): value is number {
6  return typeof value === 'number' && !isNaN(value);
7}
8
9function isObject(value: unknown): value is Record<string, unknown> {
10  return typeof value === 'object' && value !== null && !Array.isArray(value);
11}

What is Type Guards?

TypeScript type guards are functions that return a type predicate (value is Type) to narrow union types at runtime. They bridge the gap between TypeScript's static analysis and real-world dynamic data such as API responses, user inputs, and JSON payloads.

How It Works

  1. 1Define a function that returns a boolean and annotate the return type as `value is SomeType`.
  2. 2TypeScript trusts this annotation and narrows the type in the truthy branch of any if-statement that calls the guard.
  3. 3Combine multiple guards to validate complex nested objects.

Common Use Cases

  • API response validation - Narrow unknown response bodies to typed interfaces
  • Union type handling - Determine which variant of a union you are working with
  • Form validation - Check user input types before processing
  • Error handling - Distinguish Error objects from unknown thrown values

Key Benefits

  • Provides full type narrowing inside if-blocks
  • Works with any type including custom interfaces
  • No runtime library needed — pure TypeScript
  • Composable into larger validation pipelines

Common Mistakes to Avoid

  • Omitting the `value is Type` return annotation turns the function into a plain boolean predicate with no narrowing effect.
  • Using `typeof` to check for objects — it returns 'object' for null too, always add a null check.
  • Checking a non-discriminating property — pick a property that uniquely identifies the type.

Quick Tips

  • Click the "Copy" button above to copy the code to your clipboard
  • This code is production-ready and can be used in your projects immediately
  • Check out related snippets below for more typescript examples

Frequently Asked Questions

What is the difference between a type guard and a type assertion in TypeScript?

A type assertion (`as Type`) is an unsafe compile-time override with no runtime check. A type guard performs a real runtime check whose result the compiler trusts — it is always safer.

Can I use type guards with generic types?

Yes. You can write `function isArrayOf<T>(arr: unknown, guard: (x: unknown) => x is T): arr is T[]` to create reusable generic guards.

About This Typescript Code Snippet

This free typescript code snippet for type guards is production-ready and copy-paste friendly. Whether you are building a web app, API, or frontend interface, this intermediate-level example will help you implement type guards quickly and correctly.

All snippets in the Snippetly library follow typescript best practices and are tested for real-world use. You can adapt this code to work with React, Vue, Node.js, or any project that uses typescript.

Tags: types, guards, utilities  | Language: typescript  | Difficulty: intermediate  | Category: TypeScript

Build Your Own Snippet Library

Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.