Lab 12: Declaration Files

Time: 40 minutes | Level: Advanced | Docker: docker run -it --rm node:20-alpine sh

Write .d.ts declaration files for untyped libraries, augment globals, add function overloads, merge namespaces with modules, and understand the @types publishing workflow.


Step 1: Environment Setup

docker run -it --rm node:20-alpine sh
npm install -g typescript
mkdir lab12 && cd lab12
npm init -y
echo '{"compilerOptions":{"module":"commonjs","target":"es2020","strict":true,"esModuleInterop":true,"baseUrl":"."}}' > tsconfig.json

💡 Declaration files describe the shape of JavaScript code to TypeScript. They provide type information without any runtime code — TypeScript discards them at compile time.


Step 2: Basic declare module

Type an untyped JavaScript library:

# Simulate an untyped JS library
mkdir -p node_modules/myutils
cat > node_modules/myutils/index.js << 'EOF'
exports.formatDate = function(date, format) {
  // ... simplified
  return date.toISOString().split('T')[0];
};
exports.slugify = function(text) {
  return text.toLowerCase().replace(/\s+/g, '-');
};
exports.chunk = function(arr, size) {
  const chunks = [];
  for (let i = 0; i < arr.length; i += size) chunks.push(arr.slice(i, i + size));
  return chunks;
};
EOF

Step 3: Global Augmentation

Add properties to global types like Window, process, or Array:

💡 export {} at the bottom of a .d.ts file makes it a "module" (not a script). In module context, declare global {} augments the global scope. Without export {}, the file would be ambient and the declarations would apply globally by default.


Step 4: Function Overload Signatures

Describe functions with multiple call signatures:


Step 5: Namespace and Module Merging

Extend a module by adding properties and nested namespaces:

💡 Module augmentation must be in a module (file with import/export). The new declarations merge with the original declare module block at compile time.


Step 6: Namespace Declarations

Type libraries that use the global namespace pattern:


Step 7: Publishing @types Packages

Structure for contributing to DefinitelyTyped:


Step 8: Capstone — Full Declaration File Suite

📸 Verified Output:


Summary

Pattern
Syntax
Use Case

Module typing

declare module 'libname' { ... }

Type untyped JS library

Global augmentation

declare global { interface Window {...} }

Extend browser globals

Module augmentation

declare module 'x' { export ... }

Add to existing types

Overloads

Multiple function f(...) signatures

Multi-signature functions

Namespace

declare namespace MyLib { ... }

IIFE/global libraries

UMD

export = Lib; export as namespace Lib

Works with import or global

@types publishing

DefinitelyTyped structure

Community type packages

Last updated