CodeOath
← All posts
TypeScript75 min total · 21 parts

TypeScript Fundamentals: Types, Interfaces, Generics, and Why It Catches Bugs Before Runtime

Contents — Part 18 of 21: Modules and Declaration Files
Part 18 of 21 · ~1 min

Modules and Declaration Files

Any TypeScript file with a top-level import or export is treated as a module, with its own scope. Type-only imports/exports can be marked explicitly, which some build tools (and tsconfig's isolatedModules) rely on to safely strip them at compile time without needing full type information:

// types.ts
export interface User { id: number; name: string; }

// app.ts
import type { User } from "./types"; // erased entirely at compile time — no runtime import at all
import { fetchUser } from "./api";   // a real runtime import

A .d.ts file contains only type declarations, no implementation — it describes the shape of JavaScript code (often from a plain-JS library with no built-in types) without providing a runtime body itself:

// jquery.d.ts (simplified)
declare function $(selector: string): {
  hide(): void;
  show(): void;
};

Most popular JavaScript libraries either ship their own .d.ts files or have community-maintained ones published under the @types/ npm scope (e.g. @types/lodash) — installing the right @types package is usually all that's needed to get full type checking and autocomplete for a library that was never written in TypeScript itself.