On this page

Guided Exercise: Build a Safe Parser for External API Data in TypeScript

Published on August 1, 2028

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

This guided exercise walks you through building a complete, type‑safe parser for external API data in TypeScript. External data — from APIs, JSON files, or user input — arrives as the unknown type, giving you no safety guarantees. The goal is to validate this data at runtime and convert it into a properly typed structure that TypeScript can trust. You will learn to define expected types, write custom type guards, validate arrays and nested structures, use the never type for exhaustiveness checking, and handle discriminated unions. Every step is fully explained, and the code is provided so you can follow along without guessing.


Step 1: Define the Expected Data Shape​

The first step in any safe parser is to define the shape of the data you expect to receive. This becomes the target type that your validation logic will enforce.


export type Product = {

    id: number;

    title: string;

    price: number;

    tags: string[];

};

The Product type describes an object with four properties: id (a number), title (a string), price (a number), and tags (an array of strings). This is the ideal shape you want to enforce.

The reason you define the type first is that it gives you a clear target for your validation logic. Your type guards will check whether an incoming value matches this shape, and if it does, TypeScript will treat it as a Product in the rest of your code.


Step 2: Simulate External API Data​

External APIs are unpredictable. To simulate this, you create a mock API function that returns data with a deliberate error.


export async function fetchProducts(): Promise<unknown> {

    // Simulated external API response

    return JSON.parse(`

        [

            { "id": 1, "title": "Laptop", "price": 1299, "tags": ["tech"] },

            { "id": "oops", "title": "Phone", "price": 799, "tags": ["tech"] }

        ]

    `);

}

The function returns Promise<unknown> because you cannot trust the shape of external data. The second product has an id that is a string ("oops") instead of a number. This is a common real‑world problem — APIs sometimes return data with the wrong type, missing fields, or unexpected structure.

TypeScript cannot catch this at compile time because JSON.parse returns any by default. By casting the result to unknown, you force yourself to validate the data before using it. This is the safe approach.


Step 3: Write Custom Type Guards​

A type guard is a function that returns a type predicate — value is Type — telling TypeScript how to narrow a type based on runtime checks.


import { type Product } from "./types";



export function isProduct(value: unknown): value is Product {

    return (

        typeof value === "object" &&

        value !== null &&

        typeof (value as any).id === "number" &&

        typeof (value as any).title === "string" &&

        typeof (value as any).price === "number" &&

        Array.isArray((value as any).tags) &&

        (value as any).tags.every((t: unknown) => typeof t === "string")

    );

}

The isProduct function checks that the value is a non‑null object and that each property has the expected type. The as any assertions are necessary because you are checking an unknown value — you cannot access properties directly until you have verified the type.

Now you write a guard for an array of products:


export function isProductArray(value: unknown): value is Product[] {

    return Array.isArray(value) && value.every(isProduct);

}

This is a composable guard — it uses isProduct inside every. It verifies that the value is an array and that every element passes the isProduct check. Composable guards are a best practice because they allow you to build complex validation from simple, reusable pieces.


Step 4: Parse and Validate the Data​

With the guards in place, you can write the parser that fetches and validates the data.


import { fetchProducts } from "./api";

import { isProductArray } from "./guards";

import { type Product } from "./types";



export async function loadProducts(): Promise<Product[]> {

    const data: unknown = await fetchProducts();



    if (!isProductArray(data)) {

        throw new Error("Invalid product data received from API");

    }



    return data;

}

The loadProducts function first fetches the data as unknown. It then uses the isProductArray guard to validate the data. If the validation fails, it throws an error. If it passes, TypeScript narrows data to Product[], and the function returns the typed array.

This is the key pattern: the guard acts as a type assertion with runtime validation. TypeScript trusts the guard's result, so once you are inside the if block where isProductArray(data) is true, data is treated as Product[].


Step 5: Use the Parser in Your Application​

Now you can use the parser safely in your application code.


import { loadProducts } from "./parser";



async function main() {

    try {

        const products = await loadProducts();



        for (const p of products) {

            console.log(`${p.title} — $${p.price}`);

        }

    } catch (err) {

        console.error("Failed to load products:", err);

    }

}



main();

When you run this code with ts-node index.ts, you will see an error because the second product is invalid. The error is thrown in the parser, before the application logic attempts to access any invalid properties.

This is exactly what you want — the parser fails early and provides a clear error message. The application code never receives invalid data, so it never has to handle malformed objects.


Step 6: Add Exhaustiveness Checking (Bonus)​

Discriminated unions are a common pattern for modeling API responses. Extend the API to return three possible states: success, error, and loading.


export type ApiResponse =

    | { status: "success"; data: unknown }

    | { status: "error"; message: string }

    | { status: "loading" };

Now you handle all cases safely, using a switch with exhaustiveness checking.


import { type ApiResponse } from "./api";

import { isProductArray } from "./guards";



function handleResponse(res: ApiResponse) {

    switch (res.status) {

        case "success":

            if (!isProductArray(res.data)) {

                throw new Error("Invalid product data");

            }

            return res.data;



        case "error":

            throw new Error(res.message);



        case "loading":

            console.log("Loading...");

            return [];



        default:

            const _exhaustive: never = res;

            return _exhaustive;

    }

}

The default case assigns res to a variable of type never. If you forget a variant — say, you add a new status of "empty" without adding a case — TypeScript raises a compile‑time error because res would not be assignable to never.

This is industrial‑strength safety. Adding a new variant to the union forces you to update every switch statement that handles it, preventing silent runtime bugs.


Summary​

This guided exercise demonstrates how to safely handle external data in TypeScript using custom type guards, narrowing, and exhaustiveness checking. You defined a Product type, simulated an unreliable API, wrote composable guards for Product and Product[], built a parser that validates unknown data and throws on failure, and extended the solution to handle discriminated unions with the never pattern.

Every step provides complete, runnable code and explains why each check is necessary. This is the exact approach used by professional TypeScript teams to build robust, production‑ready systems that handle external data safely and maintain type integrity throughout the codebase.

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Exhaustiveness Checking

Next

Interfaces, Classes & OOP in TypeScript