Typescript Foundations / Type Declaration and third party types

Writing custom .d.ts declaration files

Custom .d.ts (declaration) files are used when:

  • You're using a JavaScript library that has no TypeScript types.

  • You're adding types for custom global values, modules, or ambient variables.

  • You're using third-party code without type definitions.


🧾 What is a .d.ts File?

.d.ts files declare the shape of modules, variables, functions, or classes without providing implementations.

They help TypeScript understand the types when the actual implementation is unknown or written in JavaScript.


📁 Folder Structure Example

src/
  index.ts
  types/
    myLib.d.ts

Make sure your tsconfig.json includes the types/ folder:

{
  "compilerOptions": {
    "typeRoots": ["./types", "./node_modules/@types"]
  }
}

🧩 Declaring a Module

If you're importing a JS file with no types:

// types/myLib.d.ts
declare module "my-lib" {
  export function greet(name: string): string;
}

Then in your code:

import { greet } from "my-lib";

🌍 Declaring Global Variables

// types/globals.d.ts
declare const VERSION: string;

Now VERSION is recognized everywhere in your code.


🏗 Declaring a Global Interface or Namespace

// types/globals.d.ts
interface Window {
  myAppVersion: string;
}

Usage:

console.log(window.myAppVersion);

Or using a namespace:

declare namespace MyApp {
  function init(): void;
}

Usage:

MyApp.init();

🛠 Declaring Functions and Objects

// types/customLib.d.ts
declare function add(a: number, b: number): number;

declare const config: {
  env: "dev" | "prod";
  debug: boolean;
};

Usage:

add(1, 2);
console.log(config.env);

📌 Notes

  • Declaration files must only contain declarations — no actual code.

  • File name must end with .d.ts.

  • TypeScript will pick them up automatically if inside typeRoots or referenced directly via /// <reference path="./types.d.ts" />.