typescript
36 lines · 8 steps
Validating API data with TypeScript type guards
Composable type guards turn untrusted JSON into a fully typed User the compiler trusts.
Explained by
highlit
1type User = {
2 id: number;
3 email: string;
4 roles: string[];
5 displayName?: string;
6};
7
8function isRecord(value: unknown): value is Record<string, unknown> {
9 return typeof value === "object" && value !== null && !Array.isArray(value);
10}
11
12function isStringArray(value: unknown): value is string[] {
13 return Array.isArray(value) && value.every((item) => typeof item === "string");
14}
15
16function isUser(value: unknown): value is User {
17 if (!isRecord(value)) return false;
18
19 if (typeof value.id !== "number") return false;
20 if (typeof value.email !== "string") return false;
21 if (!isStringArray(value.roles)) return false;
22 if ("displayName" in value && typeof value.displayName !== "string") return false;
23
24 return true;
25}
26
27async function fetchUser(id: number): Promise<User> {
28 const response = await fetch(`/api/users/${id}`);
29 const payload: unknown = await response.json();
30
31 if (!isUser(payload)) {
32 throw new TypeError(`Malformed user payload for id ${id}`);
33 }
34
35 return payload;
36}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A function returning `value is T` teaches the compiler to narrow a type after a runtime check passes.
- 2Small single-purpose guards compose into larger ones, keeping each validation step readable and reusable.
- 3Treating external data as `unknown` forces you to validate before the type system will let you use it.
Related explainers
typescript
import { Component } from '@angular/core'; import { RouterLink, RouterLinkActive } from '@angular/router'; import { NgFor } from '@angular/common';
Building an active-route navbar in Angular
routing
standalone-components
accessibility
Intermediate
6 steps
typescript
type Masker = (value: string) => string; const maskEmail: Masker = (value) => { const [local, domain] = value.split("@");
Recursively masking sensitive data for logs
recursion
regex
data-masking
Intermediate
9 steps
typescript
interface ParsedName { first: string; middle: string; last: string;
Parsing human names into structured parts
parsing
string-manipulation
normalization
Intermediate
9 steps
typescript
import { useCallback, useEffect, useRef, useState } from "react"; interface UseResendCooldownOptions { cooldownSeconds?: number;
A resend cooldown hook in React
custom-hooks
timers
state-management
Intermediate
7 steps
typescript
import { Injectable, PipeTransform, ArgumentMetadata,
A custom validation pipe in NestJS
validation
dto
recursion
Intermediate
10 steps
typescript
import { CallHandler, ExecutionContext, Injectable,
Recording HTTP metrics with a NestJS interceptor
interceptor
observability
prometheus
Intermediate
5 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/validating-api-data-with-typescript-type-guards-explained-typescript-cefa/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.