Description
Extension methods enable you to attach methods to existing types without creating a new derived type. While they may look as the are part of the class, in fact when compiled the code will use an extension method by passing the object as the first argument.
Typescript allows you to define extension methods (which then compiles to js code) and I will show you how:
Steps:
- Define an interface using the name of the type you want to extend (in our example Array)
- In the interface define the methods but ignore the first argument at this step (the first argument is the actual object)
- Define the extension on the prototype and include the first argument
/* EXTENDING ARRAY */ interface Array<T> { //Cumulative function with seed Aggregate<T, TSeed>(seed: TSeed, callback: { (seed: TSeed, current: T): TSeed }): TSeed; //checks if all elements satisfy a condition All(condition: (current: T) => boolean): boolean; //Checks if any element satisfy a condition Any(condition: (current: T) => boolean): boolean; //Returns first element. Doesn't make any checks for empty list First(): T; }
Array.prototype.Aggregate = function <T, TSeed>(this: Array, 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 (this: Array, condition: (current: T) => boolean): boolean { let all: boolean = true; for (let i = 0; i < this.length; i++) if (condition(this[i]) === false) all = false; return all; } Array.prototype.Any = function (this: Array, condition: (current: T) => boolean): boolean { let any: boolean = false; for (let i = 0; i < this.length; i++) if (condition(this[i]) === true) any = true; return any; } Array.prototype.First = function (this: Array): T { return this[0]; }