Extension methods let you attach new behaviour to existing types without subclassing. TypeScript supports this pattern through prototype extension combined with interface declaration merging. The compiled output calls the prototype method with the object as the first argument — just like JavaScript's Function.prototype.call.
Steps
- Declare an interface using the exact name of the type you want to extend (e.g.
Array) — TypeScript merges it with the built-in declaration - In the interface, declare the method signatures without the
thisparameter - On the prototype, implement the methods with
this: Array<T>as the first typed argument
Step 1 — Interface Declaration
typescript
// Step 1: Declare the new methods on the existing type's interface.
// The interface name must match the type you are extending.
interface Array<T> {
// Cumulative aggregation with a seed value (like LINQ's Aggregate)
Aggregate<T, TSeed>(
seed: TSeed,
callback: (seed: TSeed, current: T) => TSeed
): TSeed;
// Returns true if every element satisfies the condition
All(condition: (current: T) => boolean): boolean;
// Returns true if at least one element satisfies the condition
Any(condition: (current: T) => boolean): boolean;
// Returns the first element (no bounds check)
First(): T;
}Step 2 — Prototype Implementation
typescript
// Step 2: Implement on the prototype.
// The first argument is always 'this: Array<T>' — the object being extended.
Array.prototype.Aggregate = function<T, TSeed>(
this: Array<T>,
seed: TSeed,
callback: (result: TSeed, current: T) => TSeed
): TSeed {
let result: TSeed = seed;
for (let i = 0; i < this.length; i++) {
result = callback(result, this[i]);
}
return result;
};
Array.prototype.All = function<T>(
this: Array<T>,
condition: (current: T) => boolean
): boolean {
for (let i = 0; i < this.length; i++) {
if (condition(this[i]) === false) return false;
}
return true;
};
Array.prototype.Any = function<T>(
this: Array<T>,
condition: (current: T) => boolean
): boolean {
for (let i = 0; i < this.length; i++) {
if (condition(this[i]) === true) return true;
}
return false;
};
Array.prototype.First = function<T>(this: Array<T>): T {
return this[0];
};
// Usage
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.Aggregate(0, (acc, n) => acc + n); // 15
const allPos = numbers.All(n => n > 0); // true
const anyGt3 = numbers.Any(n => n > 3); // true
const first = numbers.First(); // 1