Skip to content

Modules & Namespaces#

Named Exports#

export const PI = 3.14;
export function add(a: number, b: number) { return a + b; }
export interface User { name: string; }

Default Exports#

export default class DB {
  connect() { /* ... */ }
}

Importing Modules#

import { PI, add } from "./math";
import DB from "./db";
import * as MathUtils from "./math";

Re-exporting#

export * from "./math";
export { User } from "./user";

Module Resolution (Relative vs Non-relative)#

import { User } from "./models/user";    // Relative
import { Component } from "react";       // Non-relative (node_modules)

Path Mapping (tsconfig.json)#

{
  "compilerOptions": {
    "baseUrl": "./src",
    "paths": {
      "@/*": ["*"]
    }
  }
}
// import { User } from "@/models/user";

Namespaces#

namespace Validation {
  export interface StringValidator {
    isValid(s: string): boolean;
  }
  export const numberRegexp = /^[0-9]+$/;
}

Nested Namespaces#

namespace Shapes {
  export namespace Polygons {
    export class Triangle {}
    export class Square {}
  }
}

Namespace Aliases#

import Polygons = Shapes.Polygons;
const sq = new Polygons.Square();

Ambient Modules (declare module)#

declare module "my-lib" {
  export function doSomething(): void;
}

Global Declarations#

declare global {
  interface Window {
    myConfig: any;
  }
}
window.myConfig = {};

Feature-based Structure#

src/
  features/
    auth/
      index.ts
      auth.service.ts
      auth.types.ts

Barrel Exports#

// index.ts
export * from "./user";
export * from "./product";
export * from "./order";

// Usage
import { User, Product } from "./models";