Learn
← Previous Next →

Hari 18: Module Augmentation & Declaration Merging

55 min Last updated 09 Apr 2026

Declaration Merging — Interface Bisa Di-extend Terpisah

// Di file pertama
interface Config {
    host: string;
    port: number;
}

// Di file kedua (merge dengan interface yang sama)
interface Config {
    ssl: boolean;
    timeout?: number;
}

// Hasilnya: Config punya semua 4 properti
const config: Config = {
    host: "localhost",
    port: 3000,
    ssl: true,
    timeout: 5000
};

Module Augmentation

// Menambah method ke tipe yang sudah ada
declare global {
    interface Array {
        last(): T | undefined;
        sum(this: number[]): number;
    }
    interface String {
        slugify(): string;
    }
}

// Implementasi
Array.prototype.last = function() { return this.at(-1); };
Array.prototype.sum  = function() { return this.reduce((a: number, b: number) => a + b, 0); };
String.prototype.slugify = function() {
    return this.toLowerCase().replace(/\s+/g, "-").replace(/[^\w-]/g, "");
};

console.log([1,2,3].last()); // 3
console.log([1,2,3].sum());  // 6 (array harus number[])

💡 Notice: declare global {} memungkinkan augment tipe global. prototype augmentation harus hati-hati: bisa konflik dengan library lain.

Assignment

Augment Array prototype dengan method chunk<T>(size): T[][] yang membagi array menjadi chunks. Test dengan [1..10] dibagi chunk 3.

Expected output:

Chunk 1: [1, 2, 3]
Chunk 2: [4, 5, 6]
Chunk 3: [7, 8, 9]
Chunk 4: [10]
TS index.ts
Solution
Output