Lesson 14 of 20

Modules & Namespaces

ES Modules in TypeScript

TypeScript uses the standard ES module syntax for importing and exporting code between files.

Example
// math.ts — named exports
export function add(a: number, b: number): number {
  return a + b;
}

export const PI = 3.14159;

// Default export
export default class Calculator {
  add(a: number, b: number) { return a + b; }
}

// app.ts — importing
import Calculator, { add, PI } from './math';
import type { User } from './types'; // type-only import

console.log(add(2, 3));
console.log(PI);

Type-Only Imports & Exports

TypeScript allows importing and exporting only types, which are erased during compilation.

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

export type Role = "admin" | "user" | "guest";

// app.ts — type-only imports
import type { User, Role } from './types';

// These won't generate any JavaScript code
function greet(user: User): string {
  return `Hello, ${user.name}`;
}

Declaration Files

Declaration files (.d.ts) describe the types for JavaScript libraries. Many libraries include them or they're available via DefinitelyTyped.

Example
// Install type declarations for a library
// npm install --save-dev @types/lodash
// npm install --save-dev @types/express

// Custom declaration file: global.d.ts
declare module 'my-untyped-lib' {
  export function doSomething(input: string): string;
  export const version: string;
}

// Augmenting existing types
declare global {
  interface Window {
    myApp: { version: string };
  }
}