LATEST 🚀 Welcome to Upgradix by Shrash Studio – Your destination for free technology learning and career growth.
🕘 Updated:
TypeScript

Working with JSON, Third-Party APIs & Declaration Files

TypeScript is great at protecting your code while you write it. However, the moment your app talks to the outside world—like fetching JSON from a third-party API or using an old JavaScript library—TypeScript cannot see what is actually coming in at runtime.

Working with JSON, Third-Party APIs & Declaration Files

TypeScript is great at protecting your code while you write it. However, the moment your app talks to the outside world—like fetching JSON from a third-party API or using an old JavaScript library—TypeScript cannot see what is actually coming in at runtime.

If an API suddenly changes a field name or returns null, your app can crash in production even if TypeScript showed zero errors. In this guide, we will learn how to safely validate external JSON data, use @types packages, and write custom .d.ts declaration files.

What you will learn
  • Why JSON.parse() and response.json() are risky in TypeScript.
  • How to safely validate external API data using unknown, Type Guards, and Zod.
  • How @types packages work for third-party JavaScript libraries.
  • How to write your own .d.ts declaration files for untyped scripts and global variables.
  • Real-world architecture tips and common TypeScript interview questions.

1. Why External JSON Data Is Dangerous

TypeScript types only exist during development. When your code compiles to JavaScript and runs in the browser or on Node.js, all TypeScript interfaces disappear completely.

When you call JSON.parse() or await response.json(), TypeScript returns the any type by default. Many developers simply use type assertion (as User) to silence the compiler. This is a trap because you are telling TypeScript, "Trust me, I know the shape of this data," without actually checking it.

Approach Compile-Time Safety Runtime Safety Verdict
Using any None None Avoid completely
Type Assertion (as User) Yes (Assumed) None (Crashes if API changes) Risky for external APIs
unknown + Type Guard / Zod Yes Yes (Catches bad data safely) Best practice for production

2. Safely Validating External API Data

The golden rule for external data is: treat all incoming JSON as unknown until you prove its shape at runtime. You can do this with a custom Type Guard or a validation library like Zod.

Method A: Custom Type Guard (Zero Dependencies)

A Type Guard is a simple function that checks the data at runtime and returns a special boolean type called a type predicate (like data is User).

Example 1: Validating API JSON with a Type Guard

interface User {
    id: number;
    name: string;
    email: string;
}

// Custom Type Guard function
function isUser(data: unknown): data is User {
    if (typeof data !== "object" || data === null) {
        return false;
    }

    const record = data as Record<string, unknown>;
    return (
        typeof record.id === "number" &&
        typeof record.name === "string" &&
        typeof record.email === "string"
    );
}

async function fetchUser(url: string): Promise<User> {
    const response = await fetch(url);
    const rawData: unknown = await response.json();

    if (!isUser(rawData)) {
        throw new Error("Invalid user data received from API");
    }

    // TypeScript now knows 100% that rawData is a User
    return rawData;
}

Expected output (when API returns valid JSON)

{ id: 101, name: "Anita", email: "anita@example.com" }

Writing manual Type Guards for deeply nested JSON objects gets tiring fast. In modern TypeScript projects, teams use schema validation libraries like Zod to validate data and generate TypeScript types automatically.

Example 2: Validating API data with Zod

import { z } from "zod";

// 1. Define the runtime schema
const UserSchema = z.object({
    id: z.number(),
    name: z.string(),
    email: z.string().email()
});

// 2. Automatically extract the TypeScript type
type User = z.infer<typeof UserSchema>;

async function fetchSafeUser(url: string): Promise<User> {
    const response = await fetch(url);
    const rawData: unknown = await response.json();

    // 3. Validate at runtime (throws a clear error if invalid)
    return UserSchema.parse(rawData);
}
Pro Tip: With Zod, you never have to write both an interface and a validator. You write the schema once, and z.infer keeps your TypeScript types in sync automatically.

3. How Safe API Validation Works (Workflow)

Instead of letting raw JSON flow straight into your application state, put a validation gate right at the boundary of your app.

External JSON to Safe TypeScript Data Flow

External API Raw JSON unknown Untrusted Data Runtime Validator Type Guard / Zod Valid Safe Data Typed Interface Invalid Error Handler Fail Gracefully

External JSON is captured as unknown, checked at runtime by a validator, and only allowed into your app once its shape is guaranteed.

4. Understanding @types Packages (DefinitelyTyped)

Not every npm package is written in TypeScript. Many popular libraries were originally written in plain JavaScript. When you install a plain JavaScript library, TypeScript will complain that it cannot find type declarations for it.

To solve this, the TypeScript community maintains a massive open-source repository called DefinitelyTyped. It publishes separate type definition packages under the @types/ scope.

Example 3: Installing a JavaScript library and its types

# 1. Install the actual JavaScript library
npm install lodash

# 2. Install its TypeScript types as a devDependency
npm install --save-dev @types/lodash
Step 1: Check if the library already includes types (modern libraries like Axios, Zod, and Prisma ship with built-in types, so you do not need @types).
Step 2: If TypeScript shows error TS7016: Could not find a declaration file, install the matching @types/package-name package.
Step 3: Always install @types packages with --save-dev (-D) because types are only needed during development and build time, never in production.

5. Writing Your Own .d.ts Declaration Files

What if you are using an internal company library, a brand-new npm package without @types, or a global script loaded via a <script> tag in HTML? That is when you write your own .d.ts (declaration) file.

A .d.ts file contains only type definitions. It has zero executable JavaScript code. It simply tells the TypeScript compiler, "Trust me, this module or global variable exists at runtime, and here is what its functions look like."

Case 1: Typing an Untyped Third-Party Module

Create a file named types/legacy-formatter.d.ts inside your src folder (make sure your tsconfig.json includes this folder).

Example 4: Declaring a module in a .d.ts file

// src/types/legacy-formatter.d.ts
declare module "legacy-formatter" {
    export function formatCurrency(amount: number, currencyCode: string): string;
    export function parseDate(dateText: string): Date;
}

Case 2: Typing a Global Variable (e.g., Analytics Script)

If an external script attaches an object like window.MyAnalytics to the browser, you can declare it globally so TypeScript stops complaining.

Example 5: Extending the global Window interface

// src/types/global.d.ts
export {}; // Makes this file a module so declare global works

declare global {
    interface Window {
        MyAnalytics: {
            trackEvent(eventName: string, payload?: Record<string, unknown>): void;
        };
    }
}
Watch out: Never put actual runtime logic (like console.log or function bodies) inside a .d.ts file. TypeScript completely ignores .d.ts files when generating JavaScript output.

6. Hands-On Practice

Beginner Exercise 1: Write a Product Type Guard

Create an interface Product with sku: string and price: number. Write a function isProduct(data: unknown): data is Product that safely verifies incoming JSON.

Hint: Check typeof data === "object" && data !== null first before checking the properties.

Intermediate Exercise 2: Validate an Array of Users with Zod

Take the UserSchema from Example 2 and use z.array(UserSchema) to validate a JSON array returned from an API endpoint.

Expected result: Valid arrays return a strongly typed User[], while an array with one missing email throws a ZodError.

Advanced Exercise 3: Declare a Custom Asset Import

Create a src/types/assets.d.ts file that allows TypeScript to import .svg files as strings without throwing a module-not-found error.

Hint: Use declare module "*.svg" and export a default string.

7. Interview Questions

Q1. Why should you prefer unknown over any when parsing JSON?

Answer: any turns off TypeScript's type checking completely, allowing runtime crashes if the JSON shape is unexpected. unknown forces you to narrow or validate the type (using a Type Guard or schema validator) before you can access any properties on it.

Q2. What is the purpose of a .d.ts file?

Answer: A .d.ts (declaration) file provides type information about existing JavaScript code to the TypeScript compiler. It enables autocomplete, type checking, and IntelliSense for untyped JavaScript libraries, global variables, or non-JS assets without emitting any runtime JavaScript.

Q3. Why are @types/* packages installed in devDependencies instead of dependencies?

Answer: Because TypeScript types are erased during compilation. Production servers only run the compiled JavaScript, so shipping @types packages in production dependencies just bloats your deployment unnecessarily.

Conclusion

TypeScript protects everything inside your codebase, but external JSON and third-party JavaScript libraries sit outside that safety net. By treating API responses as unknown, validating them at runtime with Type Guards or Zod, and using @types or custom .d.ts files for external code, you keep your application rock-solid in production.

Official Documentation

Upgradix by Shrash Studio – Learn Technology. Build Your Future.

Comments & Ratings (0)

Log in or create a student account to comment and rate this article.

Be the first to comment on this article.