Kurs JavaScript i TypeScript · Moduł 10: TypeScript w praktyce

Module augmentation i declaration merging

13 min czytania ·
W tej lekcji3

Wyobraź sobie, że park kupił gotowy system kamer, a Ty chcesz dopisać do jego raportów pole dinosaurId. Nie możesz edytować kodu dostawcy, bo zniknie przy następnej aktualizacji. Module augmentation i declaration merging to zaawansowane funkcje TypeScript, które pozwalają rozszerzać istniejące moduły i łączyć deklaracje bez ruszania oryginału. Te mechanizmy są kluczowe przy pracy z bibliotekami zewnętrznymi, tworzeniu pluginów i rozszerzaniu frameworków.

Declaration Merging

Declaration merging (łączenie deklaracji) oznacza, że kompilator skleja kilka deklaracji o tej samej nazwie w jedną definicję. Dotyczy to interfejsów, przestrzeni nazw (namespace) oraz par: klasa z namespace, funkcja z namespace i enum z namespace. Nie łączą się natomiast aliasy typów (type) ani dwie klasy o tej samej nazwie.

Podstawy declaration merging

Najczęstszy przypadek to dwa interfejsy o tej samej nazwie. Obok widać łączenie przestrzeni nazw oraz klasy z namespace, który dokłada do klasy typy i funkcje statyczne:

// Interface merging - najczęstszy przypadek
interface User {
  id: number;
  name: string;
}

interface User {
  email: string;  // Dodajemy nową właściwość
  age?: number;   // I kolejną opcjonalną
}

// TypeScript automatycznie łączy obie deklaracje
const user: User = {
  id: 1,
  name: "Jan Kowalski",
  email: "jan@example.com"
  // age jest opcjonalne
};

// Namespace merging
namespace MyApp {
  export interface Config {
    apiUrl: string;
  }

  export function initialize(config: Config): void {
    console.log("Inicjalizacja z:", config.apiUrl);
  }
}

namespace MyApp {
  export interface Config {
    timeout?: number;  // Rozszerzamy interfejs Config
  }

  export class Logger {
    log(message: string): void {
      console.log(`[MyApp]: ${message}`);
    }
  }
}

// Używamy połączonych deklaracji
const config: MyApp.Config = {
  apiUrl: "https://api.example.com",
  timeout: 5000
};

const logger = new MyApp.Logger();
logger.log("Aplikacja uruchomiona");

// Class and namespace merging
class Album {
  constructor(public title: string, public artist: string) {}
}

namespace Album {
  export interface Track {
    number: number;
    title: string;
    duration: number;
  }

  export function createFromJSON(json: string): Album {
    const data = JSON.parse(json);
    return new Album(data.title, data.artist);
  }
}

// Używamy klasy i namespace razem
const album = new Album("The Wall", "Pink Floyd");
const track: Album.Track = {
  number: 1,
  title: "In The Flesh?",
  duration: 196
};

const albumFromJSON = Album.createFromJSON('{"title": "Dark Side", "artist": "Pink Floyd"}');

Obiekt user musi mieć pola z obu deklaracji, a Album działa jednocześnie jako klasa (new Album(...)) i jako przestrzeń nazw (Album.Track). Jeśli oba interfejsy deklarują to samo pole, jego typy muszą być identyczne, inaczej kompilator zgłosi błąd.

Funkcje i namespace merging

Funkcja połączona z namespace to obiekt, który można wywołać i który ma dodatkowe pola, jak w wielu bibliotekach JavaScript. To samo działa z enumem:

// Function and namespace merging - przydatne dla tworzenia callable objects
function createCounter(initial: number = 0): () => number {
  let count = initial;
  return () => ++count;
}

namespace createCounter {
  export interface Options {
    initial?: number;
    step?: number;
    max?: number;
  }

  export function withOptions(options: Options): () => number {
    let count = options.initial || 0;
    const step = options.step || 1;
    const max = options.max || Infinity;

    return () => {
      if (count + step > max) {
        return count;
      }
      count += step;
      return count;
    };
  }

  export function reset(counter: () => number): void {
    // Implementacja resetu
    console.log("Counter reset");
  }
}

// Używamy funkcji i jej namespace
const counter1 = createCounter(10);
const counter2 = createCounter.withOptions({ initial: 0, step: 5, max: 100 });

console.log(counter1()); // 11
console.log(counter2()); // 5
createCounter.reset(counter1);

// Enum and namespace merging
enum Status {
  Idle = "IDLE",
  Loading = "LOADING",
  Success = "SUCCESS",
  Error = "ERROR"
}

namespace Status {
  export function isComplete(status: Status): boolean {
    return status === Status.Success || status === Status.Error;
  }

  export function isInProgress(status: Status): boolean {
    return status === Status.Loading;
  }

  export interface Metadata {
    timestamp: Date;
    message?: string;
  }
}

// Używamy enum z dodatkowymi funkcjami
const currentStatus = Status.Loading;
console.log(Status.isInProgress(currentStatus)); // true
console.log(Status.isComplete(currentStatus));   // false

createCounter(10) zwraca licznik startujący od 10, a createCounter.withOptions to funkcja podpięta pod tę samą nazwę. Enum Status dostał metody pomocnicze, a jego wartości się nie zmieniły.

Merging z generics

Łączone interfejsy generyczne muszą mieć identyczne parametry typu, łącznie z nazwami. Klasa implementuje wtedy sumę wszystkich deklaracji:

// Generic interface merging
interface Collection<T> {
  items: T[];
  add(item: T): void;
}

interface Collection<T> {
  remove(item: T): boolean;
  find(predicate: (item: T) => boolean): T | undefined;
}

class ArrayCollection<T> implements Collection<T> {
  items: T[] = [];

  add(item: T): void {
    this.items.push(item);
  }

  remove(item: T): boolean {
    const index = this.items.indexOf(item);
    if (index > -1) {
      this.items.splice(index, 1);
      return true;
    }
    return false;
  }

  find(predicate: (item: T) => boolean): T | undefined {
    return this.items.find(predicate);
  }
}

// Generic namespace merging
namespace DataStructures {
  export interface Node<T> {
    value: T;
    next?: Node<T>;
  }

  export class LinkedList<T> {
    head?: Node<T>;

    add(value: T): void {
      const node: Node<T> = { value };
      if (!this.head) {
        this.head = node;
      } else {
        let current = this.head;
        while (current.next) {
          current = current.next;
        }
        current.next = node;
      }
    }
  }
}

namespace DataStructures {
  export interface Node<T> {
    prev?: Node<T>;  // Dodajemy wskaźnik do poprzedniego elementu
  }

  export class DoublyLinkedList<T> extends LinkedList<T> {
    // Implementacja listy dwukierunkowej
  }
}

ArrayCollection musi mieć add, remove i find, bo Collection<T> to już jeden interfejs. Druga część namespace DataStructures dokłada do węzła wskaźnik prev.

Module Augmentation

Module augmentation to rozszerzanie typów z cudzego modułu. Importujesz oryginalny moduł (co czyni plik modułem), otwierasz jego deklarację przez declare module 'nazwa', dodajesz nowe pola lub metody do interfejsu, a TypeScript sam łączy deklaracje. Dla pliku lokalnego napiszesz na przykład declare module './dinosaur' { interface Dinosaur { fly(): void } }.

Rozszerzanie modułów zewnętrznych

Dodajemy do żądania Express dane użytkownika, a do odpowiedzi metody pomocnicze. Rozszerzamy express-serve-static-core, bo stamtąd pochodzą typy req i res w handlerach:

// Rozszerzanie typów Express (req i res w handlerach pochodzą z express-serve-static-core)
declare module "express-serve-static-core" {
  interface Request {
    user?: {
      id: string;
      email: string;
      roles: string[];
    };
    requestId?: string;
  }

  interface Response {
    sendSuccess(data: any): void;
    sendError(error: Error, statusCode?: number): void;
  }
}

// Implementacja rozszerzeń
import express from "express";

const app = express();

// Middleware dodający user i requestId
app.use((req, res, next) => {
  req.requestId = crypto.randomUUID();
  // Autentykacja i dodanie użytkownika
  req.user = {
    id: "123",
    email: "user@example.com",
    roles: ["user", "admin"]
  };
  next();
});

// Rozszerzenie Response o nowe metody
app.use((req, res, next) => {
  res.sendSuccess = function(data: any) {
    this.json({
      success: true,
      data,
      requestId: req.requestId
    });
  };

  res.sendError = function(error: Error, statusCode: number = 500) {
    this.status(statusCode).json({
      success: false,
      error: error.message,
      requestId: req.requestId
    });
  };

  next();
});

// Używamy rozszerzonych typów
app.get("/profile", (req, res) => {
  if (!req.user) {
    return res.sendError(new Error("Unauthorized"), 401);
  }

  res.sendSuccess({
    user: req.user,
    requestId: req.requestId
  });
});

Augmentacja zmienia tylko typy, więc implementację sendSuccess i sendError nadal dodaje middleware, zanim użyje ich handler. Zasada ogólna: rozszerzaj moduł, który faktycznie deklaruje typ, a nie ten, który go tylko re-eksportuje.

Rozszerzanie globalnych typów

Blok declare global rozszerza typy globalne, takie jak Window, Array czy String. Działa tylko w pliku, który jest modułem, więc jeśli plik nie ma importów, dodaj na końcu export {}:

// Rozszerzanie globalnych obiektów
declare global {
  interface Window {
    myApp: {
      version: string;
      config: {
        apiUrl: string;
        debugMode: boolean;
      };
      utils: {
        formatDate(date: Date): string;
        parseJSON<T>(json: string): T | null;
      };
    };
  }

  interface Array<T> {
    groupBy<K extends keyof T>(key: K): Record<string, T[]>;
    chunk(size: number): T[][];
  }

  interface String {
    capitalize(): string;
    toSlug(): string;
  }
}

// Implementacja rozszerzeń Array
Array.prototype.groupBy = function<T, K extends keyof T>(this: T[], key: K): Record<string, T[]> {
  return this.reduce((acc, item) => {
    const groupKey = String(item[key]);
    if (!acc[groupKey]) {
      acc[groupKey] = [];
    }
    acc[groupKey].push(item);
    return acc;
  }, {} as Record<string, T[]>);
};

Array.prototype.chunk = function<T>(this: T[], size: number): T[][] {
  const chunks: T[][] = [];
  for (let i = 0; i < this.length; i += size) {
    chunks.push(this.slice(i, i + size));
  }
  return chunks;
};

// Implementacja rozszerzeń String
String.prototype.capitalize = function(this: string): string {
  return this.charAt(0).toUpperCase() + this.slice(1).toLowerCase();
};

String.prototype.toSlug = function(this: string): string {
  return this
    .toLowerCase()
    .trim()
    .replace(/[^\w\s-]/g, '')
    .replace(/[\s_-]+/g, '-')
    .replace(/^-+|-+$/g, '');
};

// Używamy rozszerzeń
const users = [
  { name: "Jan", age: 30, department: "IT" },
  { name: "Anna", age: 25, department: "HR" },
  { name: "Piotr", age: 35, department: "IT" }
];

const grouped = users.groupBy("department");
console.log(grouped); // { IT: [...], HR: [...] }

const chunks = [1, 2, 3, 4, 5, 6, 7, 8].chunk(3);
console.log(chunks); // [[1, 2, 3], [4, 5, 6], [7, 8]]

const title = "hello world from typescript".capitalize();
console.log(title); // "Hello world from typescript"

const slug = "Hello World! From TypeScript".toSlug();
console.log(slug); // "hello-world-from-typescript"

// Window rozszerzenia
window.myApp = {
  version: "1.0.0",
  config: {
    apiUrl: "https://api.example.com",
    debugMode: true
  },
  utils: {
    formatDate(date: Date): string {
      return date.toLocaleDateString("pl-PL");
    },
    parseJSON<T>(json: string): T | null {
      try {
        return JSON.parse(json) as T;
      } catch {
        return null;
      }
    }
  }
};

Technicznie to działa, ale rozszerzania wbudowanych prototypów nie polecam. Właśnie takie łatki (biblioteka Sugar dopisywała tablicom własne groupBy) sprawiły, że standard nie mógł użyć nazwy Array.prototype.groupBy i w ES2024 powstało statyczne Object.groupBy. Bezpieczniej pisać zwykłe funkcje pomocnicze albo rozszerzać własne obiekty, jak window.myApp.

Plugin system z module augmentation

System pluginów pozwala różnym częściom aplikacji dopisywać własne typy kontekstu i hooków do wspólnego modułu:

// Bazowy system pluginów
interface PluginSystem {
  plugins: Map<string, Plugin>;
  register(plugin: Plugin): void;
  execute(hookName: string, context: any): void;
}

interface Plugin {
  name: string;
  version: string;
  hooks?: {
    [hookName: string]: (context: any) => void | Promise<void>;
  };
}

class PluginManager implements PluginSystem {
  plugins = new Map<string, Plugin>();

  register(plugin: Plugin): void {
    this.plugins.set(plugin.name, plugin);
    console.log(`Plugin ${plugin.name} v${plugin.version} zarejestrowany`);
  }

  async execute(hookName: string, context: any): Promise<void> {
    for (const [name, plugin] of this.plugins) {
      if (plugin.hooks && plugin.hooks[hookName]) {
        await plugin.hooks[hookName](context);
      }
    }
  }
}

// Rozszerzanie systemu pluginów przez różne moduły
declare module "./plugin-system" {
  interface PluginContext {
    user?: {
      id: string;
      name: string;
    };
    request?: {
      url: string;
      method: string;
    };
  }

  interface PluginHooks {
    beforeRequest?: (context: PluginContext) => void;
    afterRequest?: (context: PluginContext & { response: any }) => void;
    onError?: (context: PluginContext & { error: Error }) => void;
  }
}

// Plugin autentykacji
const authPlugin: Plugin = {
  name: "auth",
  version: "1.0.0",
  hooks: {
    beforeRequest(context) {
      console.log("Sprawdzanie autentykacji...");
      if (!context.user) {
        throw new Error("Brak autentykacji");
      }
    }
  }
};

// Plugin logowania
const loggingPlugin: Plugin = {
  name: "logging",
  version: "1.0.0",
  hooks: {
    beforeRequest(context) {
      console.log(`[${new Date().toISOString()}] ${context.request?.method} ${context.request?.url}`);
    },
    afterRequest(context) {
      console.log(`Response dla ${context.request?.url}:`, context.response);
    },
    onError(context) {
      console.error(`Błąd dla ${context.request?.url}:`, context.error);
    }
  }
};

// Używanie systemu pluginów
const pluginManager = new PluginManager();
pluginManager.register(authPlugin);
pluginManager.register(loggingPlugin);

// Symulacja żądania
const context = {
  user: { id: "123", name: "Jan" },
  request: { url: "/api/data", method: "GET" }
};

pluginManager.execute("beforeRequest", context);

Augmentacja declare module './plugin-system' działa tylko wtedy, gdy taki plik istnieje, a sam kod musi leżeć w module. W pliku bez importów interfejs Plugin połączyłby się z globalnym interfejsem Plugin z definicji DOM, opisującym wtyczki przeglądarki. To declaration merging w najmniej pożądanej postaci.

Praktyczne zastosowania

Rozszerzanie bibliotek UI

Material UI wprost zachęca do augmentacji: własne pola motywu i warianty typografii dopisujesz do interfejsów Theme, ThemeOptions i TypographyVariants:

// Rozszerzanie Material-UI
declare module "@mui/material/styles" {
  interface Theme {
    custom: {
      borderRadius: {
        small: number;
        medium: number;
        large: number;
      };
      animations: {
        fast: string;
        normal: string;
        slow: string;
      };
    };
  }

  interface ThemeOptions {
    custom?: {
      borderRadius?: {
        small?: number;
        medium?: number;
        large?: number;
      };
      animations?: {
        fast?: string;
        normal?: string;
        slow?: string;
      };
    };
  }

  interface TypographyVariants {
    label: React.CSSProperties;
    caption2: React.CSSProperties;
  }

  interface TypographyVariantsOptions {
    label?: React.CSSProperties;
    caption2?: React.CSSProperties;
  }
}

declare module "@mui/material/Typography" {
  interface TypographyPropsVariantOverrides {
    label: true;
    caption2: true;
  }
}

// Tworzenie rozszerzonego theme
import { createTheme } from "@mui/material/styles";

const theme = createTheme({
  custom: {
    borderRadius: {
      small: 4,
      medium: 8,
      large: 16
    },
    animations: {
      fast: "150ms",
      normal: "300ms",
      slow: "500ms"
    }
  },
  typography: {
    label: {
      fontSize: "0.75rem",
      fontWeight: 600,
      textTransform: "uppercase"
    },
    caption2: {
      fontSize: "0.625rem",
      fontWeight: 400
    }
  }
});

// Używanie rozszerzonych typów
import { Typography, Box } from "@mui/material";

function CustomComponent() {
  return (
    <Box
      sx={{
        borderRadius: (theme) => theme.custom.borderRadius.medium,
        transition: (theme) => `all ${theme.custom.animations.normal} ease`
      }}
    >
      <Typography variant="label">Custom Label</Typography>
      <Typography variant="caption2">Tiny caption text</Typography>
    </Box>
  );
}

Theme opisuje gotowy motyw, a ThemeOptions dane przekazywane do createTheme, dlatego tam pola są opcjonalne. Kod zawiera JSX, więc w projekcie trzymasz go w pliku .tsx.

Rozszerzanie frameworków

Tak samo rozszerzysz typy Next.js dla API routes z Pages Router, dokładając sesję i metody pomocnicze:

// Rozszerzanie Next.js
declare module "next" {
  export interface NextApiRequest {
    session?: {
      user: {
        id: string;
        email: string;
        permissions: string[];
      };
      expiresAt: Date;
    };

    // Metody pomocnicze
    validateBody<T>(schema: any): T;
    requireAuth(): void;
    hasPermission(permission: string): boolean;
  }

  export interface NextApiResponse {
    success<T>(data: T, statusCode?: number): void;
    error(message: string, statusCode?: number): void;
    paginated<T>(items: T[], total: number, page: number, pageSize: number): void;
  }
}

// Middleware rozszerzające Next.js
import { NextApiRequest, NextApiResponse } from "next";

export function withExtensions(
  handler: (req: NextApiRequest, res: NextApiResponse) => Promise<void>
) {
  return async (req: NextApiRequest, res: NextApiResponse) => {
    // Dodaj metody do request
    req.validateBody = function<T>(schema: any): T {
      // Implementacja walidacji
      return req.body as T;
    };

    req.requireAuth = function() {
      if (!this.session) {
        throw new Error("Authentication required");
      }
    };

    req.hasPermission = function(permission: string): boolean {
      return this.session?.user.permissions.includes(permission) || false;
    };

    // Dodaj metody do response
    res.success = function<T>(data: T, statusCode = 200) {
      this.status(statusCode).json({
        success: true,
        data
      });
    };

    res.error = function(message: string, statusCode = 500) {
      this.status(statusCode).json({
        success: false,
        error: message
      });
    };

    res.paginated = function<T>(items: T[], total: number, page: number, pageSize: number) {
      this.json({
        success: true,
        data: items,
        pagination: {
          total,
          page,
          pageSize,
          totalPages: Math.ceil(total / pageSize)
        }
      });
    };

    // Wywołaj handler
    try {
      await handler(req, res);
    } catch (error) {
      res.error(error instanceof Error ? error.message : "Internal server error");
    }
  };
}

// Użycie w API route
export default withExtensions(async (req, res) => {
  req.requireAuth();

  if (!req.hasPermission("read:users")) {
    return res.error("Insufficient permissions", 403);
  }

  const data = req.validateBody<{ search?: string }>(/* schema */);

  // Logika biznesowa
  const users = []; // Pobierz użytkowników
  const total = 100;

  res.paginated(users, total, 1, 20);
});

W App Router trasy API obsługują Route Handlers oparte na standardowych obiektach Request i Response, więc tam zamiast augmentacji zwykle piszesz funkcje pomocnicze. Przy typach re-eksportowanych sprawdź, z którego pliku pochodzą, tak jak w przypadku Expressa.

Module augmentation i declaration merging to potężne narzędzia do elastycznego rozszerzania istniejącego kodu. Kluczem jest zrozumienie, kiedy używać każdej techniki i jak mogą współpracować w rozszerzalnych systemach. Moja rada: augmentacje trzymaj w osobnym katalogu, na przykład types/, żeby cały zespół wiedział, gdzie szukać dopisków do cudzych typów. W edytorze poniżej przećwiczysz łączenie deklaracji, a w kolejnej lekcji poznasz Test-Driven Development.

Pamiętaj: augmentacja to naklejka z dopiskiem na cudzej mapie parku, która niczego nie wymazuje, tylko dodaje nowe informacje.

Kod do tej lekcji: index.ts
// Przykłady module augmentation i declaration merging

// 1. Interface merging - łączenie deklaracji
interface User {
  id: number;
  name: string;
}

interface User {
  email: string;    // Dodajemy nowe właściwości
  age?: number;     // Opcjonalna właściwość
}

// TypeScript automatycznie łączy obie deklaracje
const user: User = {
  id: 1,
  name: "Jan Kowalski",
  email: "jan@example.com",
  age: 30
};

// 2. Namespace merging
namespace AppConfig {
  export interface Settings {
    apiUrl: string;
    timeout: number;
  }

  export function getDefaultSettings(): Settings {
    return {
      apiUrl: "https://api.example.com",
      timeout: 5000
    };
  }
}

namespace AppConfig {
  export interface Settings {
    debugMode?: boolean;  // Rozszerzamy interfejs
  }

  export class ConfigManager {
    private settings: Settings;

    constructor() {
      this.settings = getDefaultSettings();
    }

    updateSettings(updates: Partial<Settings>): void {
      this.settings = { ...this.settings, ...updates };
    }

    getSettings(): Settings {
      return this.settings;
    }
  }
}

// Używamy połączonych deklaracji
const configManager = new AppConfig.ConfigManager();
configManager.updateSettings({ debugMode: true });
console.log("Ustawienia:", configManager.getSettings());

// 3. Function i namespace merging
function createLogger(prefix: string) {
  return {
    log(message: string) {
      console.log(`[${prefix}] ${message}`);
    }
  };
}

namespace createLogger {
  export interface Options {
    timestamp?: boolean;
    color?: string;
  }

  export function withOptions(prefix: string, options: Options) {
    return {
      log(message: string) {
        const timestamp = options.timestamp ? new Date().toISOString() : '';
        console.log(`${timestamp} [${prefix}] ${message}`);
      }
    };
  }

  export const DEFAULT_OPTIONS: Options = {
    timestamp: true,
    color: 'default'
  };
}

// Używamy funkcji i namespace
const logger1 = createLogger("APP");
const logger2 = createLogger.withOptions("DEBUG", { timestamp: true });

logger1.log("Prosta wiadomość");
logger2.log("Wiadomość z timestampem");

// 4. Rozszerzanie globalnych typów
declare global {
  interface Array<T> {
    first(): T | undefined;
    last(): T | undefined;
    groupBy<K extends keyof T>(key: K): Record<string, T[]>;
  }

  interface String {
    capitalize(): string;
    toKebabCase(): string;
  }
}

// Implementacja rozszerzeń
Array.prototype.first = function<T>(this: T[]): T | undefined {
  return this[0];
};

Array.prototype.last = function<T>(this: T[]): T | undefined {
  return this[this.length - 1];
};

Array.prototype.groupBy = function<T, K extends keyof T>(
  this: T[],
  key: K
): Record<string, T[]> {
  return this.reduce((groups, item) => {
    const groupKey = String(item[key]);
    groups[groupKey] = groups[groupKey] || [];
    groups[groupKey].push(item);
    return groups;
  }, {} as Record<string, T[]>);
};

String.prototype.capitalize = function(this: string): string {
  return this.charAt(0).toUpperCase() + this.slice(1);
};

String.prototype.toKebabCase = function(this: string): string {
  return this
    .replace(/([A-Z])/g, '-$1')
    .toLowerCase()
    .replace(/^-/, '');
};

// Test rozszerzeń
const numbers = [1, 2, 3, 4, 5];
console.log("Pierwszy element:", numbers.first());  // 1
console.log("Ostatni element:", numbers.last());    // 5

const products = [
  { name: "Laptop", category: "Electronics", price: 1000 },
  { name: "Mouse", category: "Electronics", price: 50 },
  { name: "Desk", category: "Furniture", price: 300 }
];

const grouped = products.groupBy("category");
console.log("Pogrupowane produkty:", grouped);

const text = "hello world";
console.log("Capitalize:", text.capitalize());  // "Hello world"

const camelCase = "myVariableName";
console.log("Kebab case:", camelCase.toKebabCase());  // "my-variable-name"

// 5. Class i namespace merging
class EventEmitter {
  private events: Map<string, Function[]> = new Map();

  on(event: string, handler: Function): void {
    if (!this.events.has(event)) {
      this.events.set(event, []);
    }
    this.events.get(event)!.push(handler);
  }

  emit(event: string, ...args: any[]): void {
    const handlers = this.events.get(event);
    if (handlers) {
      handlers.forEach(handler => handler(...args));
    }
  }
}

namespace EventEmitter {
  export interface EventMap {
    connect: { userId: string; timestamp: Date };
    disconnect: { userId: string; reason: string };
    message: { userId: string; text: string };
  }

  export type EventHandler<K extends keyof EventMap> =
    (data: EventMap[K]) => void;

  export function createTypedEmitter() {
    const emitter = new EventEmitter();

    return {
      on<K extends keyof EventMap>(event: K, handler: EventHandler<K>): void {
        emitter.on(event, handler);
      },

      emit<K extends keyof EventMap>(event: K, data: EventMap[K]): void {
        emitter.emit(event, data);
      }
    };
  }
}

// Używamy typed event emitter
const typedEmitter = EventEmitter.createTypedEmitter();

typedEmitter.on('connect', (data) => {
  console.log(`Użytkownik ${data.userId} połączył się o ${data.timestamp}`);
});

typedEmitter.on('message', (data) => {
  console.log(`${data.userId}: ${data.text}`);
});

typedEmitter.emit('connect', {
  userId: 'user123',
  timestamp: new Date()
});

typedEmitter.emit('message', {
  userId: 'user123',
  text: 'Witaj wszystkim!'
});

// 6. Module augmentation (symulacja)
// W prawdziwej aplikacji byłoby to w osobnym pliku
interface MyLibrary {
  version: string;
  utils: {
    formatDate(date: Date): string;
  };
}

// Rozszerzamy bibliotekę
interface MyLibrary {
  plugins: Plugin[];
  registerPlugin(plugin: Plugin): void;
}

interface Plugin {
  name: string;
  init(): void;
}

// Implementacja rozszerzonej biblioteki
const myLibrary: MyLibrary = {
  version: "1.0.0",
  utils: {
    formatDate(date: Date): string {
      return date.toLocaleDateString('pl-PL');
    }
  },
  plugins: [],
  registerPlugin(plugin: Plugin): void {
    this.plugins.push(plugin);
    plugin.init();
    console.log(`Plugin ${plugin.name} zarejestrowany`);
  }
};

// Test
const datePlugin: Plugin = {
  name: "DateFormatter",
  init() {
    console.log("DateFormatter plugin zainicjowany");
  }
};

myLibrary.registerPlugin(datePlugin);
console.log("Wersja biblioteki:", myLibrary.version);
console.log("Sformatowana data:", myLibrary.utils.formatDate(new Date()));

// Export dla uniknięcia błędów globalnych deklaracji
export {};

Hasła z dokumentacji w tej lekcji

Widzisz błąd w tej lekcji?

Sprawdź się

Odpowiedz na pytania z tej lekcji. Wybierz odpowiedź, a od razu zobaczysz, czy jest poprawna.

  1. 1. Które deklaracje mogą być automatycznie mergowane w TypeScript?

Zadania praktyczne w grze

  • Klikanie w kolejności

    Uporządkuj kroki tworzenia ambient modules.

  • Edytor kodu

    Rozszerz istniejące typy przez declaration merging.

  • Klikanie w kolejności

    Ułóż elementy deklaracji module augmentation:

  • Układanie w pionie

    Ułóż kroki rozszerzania modułu przez module augmentation:

  1. PytanieDeclaration merging typy
  2. Kliknij w kolejnościAmbient modules
  3. Zadanie z kodemĆwiczenie: Module augmentation
  4. Kliknij w kolejnościSkładnia module augmentation
  5. Ułóż w kolejnościProces module augmentation

Przydatne artykuły