Menu

Declaration Files and types Packages

Lesson 2: Declaration Files and @types Packages

What is a declaration file?

A declaration file (.d.ts) contains only types, no implementation. It describes the shape of JavaScript code so TypeScript can check how you use it.

Source of types Example How you get it
Bundled with the package zod, date-fns, axios Automatically, via the package's types field
DefinitelyTyped @types package @types/node, @types/express npm install -D @types/node
Your own declarations An internal or untyped library Write a .d.ts file
Generated from your code Your library's public API "declaration": true in tsconfig.json

Example

Install Node.js types and list them in tsconfig.json:

npm install -D @types/node
{
  "compilerOptions": {
    "types": ["node"]
  }
}

Declare types for an untyped package:

// src/types/legacy-sms.d.ts
declare module 'legacy-sms' {
  export function sendSms(phone: string, message: string): Promise<{ id: string }>;
}

Add types for global values and file imports:

// src/types/globals.d.ts
declare global {
  interface Window {
    analytics?: { track(event: string, data?: Record<string, unknown>): void };
  }
}

declare module '*.svg' {
  const src: string;
  export default src;
}

export {};

How it works

  • Since TypeScript 6.0, the types option defaults to [], so @types packages are not loaded automatically. List the ones you need, such as "node" or "jest". This also speeds up builds.
  • declare module 'name' adds types for a package that has none.
  • declare global extends global types such as Window. The export {} makes the file a module so declare global is allowed.
  • Libraries publish .d.ts files generated with declaration: true so users get types automatically.

Common mistakes

Mistake Effect Fix
Installing @types/node but process is still unknown types defaults to [] in TypeScript 6+ Add "types": ["node"]
declare module 'x' with no body Every import from it is any Write the real signatures you use
Installing @types for packages that ship their own types Conflicting definitions Check the package first; remove the extra @types

Key takeaways

  • .d.ts files describe JavaScript without implementing it.
  • In TypeScript 6+, list global type packages explicitly in types.

Try it: Write a .d.ts file for an imaginary untyped pincode-lookup package with a lookup(pincode: string): Promise<{ city: string; state: string }> function.


TypeScript Tutorial

J

Jebasta





Get in Touch For Details