S SmartDocs
Série: Typescript typescript 106 linhas · Atualizado 2025-12-27

04-modules-namespaces.ts

Typescript/src/02-intermediate/04-modules-namespaces.ts

// ============================================
// 04. Modules and Namespaces
// ============================================

// ES6 Modules - Export
export function add(a: number, b: number): number {
  return a + b;
}

export function subtract(a: number, b: number): number {
  return a - b;
}

export const PI = 3.14159;

// Default export
export default function multiply(a: number, b: number): number {
  return a * b;
}

// Import example (would be in another file):
// import multiply, { add, subtract, PI } from "./04-modules-namespaces";

// Type-Only Imports/Exports
export type User = {
  name: string;
  age: number;
};

export interface Product {
  id: number;
  name: string;
}

// Import example:
// import type { User, Product } from "./04-modules-namespaces";

// Namespaces
namespace MathUtils {
  export function add(a: number, b: number): number {
    return a + b;
  }

  export function subtract(a: number, b: number): number {
    return a - b;
  }

  export const PI = 3.14159;
}

// Usage
console.log(MathUtils.add(5, 3));
console.log(MathUtils.PI);

// Nested Namespaces
namespace Geometry {
  export namespace Circle {
    export function area(radius: number): number {
      return Math.PI * radius ** 2;
    }
  }

  export namespace Rectangle {
    export function area(width: number, height: number): number {
      return width * height;
    }
  }
}

console.log(Geometry.Circle.area(5));
console.log(Geometry.Rectangle.area(4, 6));

// Merging Namespaces
namespace MyLib {
  export function doSomething() {
    console.log("Doing something");
  }
}

namespace MyLib {
  export function doSomethingElse() {
    console.log("Doing something else");
  }
}

// Both functions are available
MyLib.doSomething();
MyLib.doSomethingElse();

// Interface Merging
interface UserInterface {
  name: string;
}

interface UserInterface {
  age: number;
}

// Merged: { name: string; age: number; }
const user: UserInterface = {
  name: "Alice",
  age: 25
};

export { MathUtils, Geometry, MyLib };

Artigos relacionados