Sunday, February 11, 2018

Extension method / Type Extension in TypeScript

During programming, most of the developers encounter scenario where there is need of adding behavior (method / operation) to existing type provide by framework (mostly by language) or into the type provided by third party library, which one can use in project multiple places without rewriting code again and again. And can access the extension code easily.

For example one want to extend Date Type and wants to add compareDate, so that it get attached to Date type as given in below image. just to note Date type is already provided Typescript language.


how to achieve behavior like that, answer is extension method.

Extension method
Extension method (programming language C# has this feature already) is way to extend existing type without modifying actual code file, means with help of the extension method one can add behavior (operation or method) without touching or modifying actual implementation file.
Now question arise how to create extension method, answer is by making use of Declaration Merging.

Declaration merging
Declaration merging in typescript allows to merge two declaration, for example if do like as below in typescript
 
interface User {
    name: string;
    id: number;
}

interface User {
    email: string;
}

and when create object of user as below


email is also part of User object as in above screen shot, it because of declaration merging. Compiler under the hood create User type as given below as it merge both the declaration of User interface defined above.
 
interface User {
    name: string;
    id: number;
    email: string;
}

Extension method on Date Type
So based on declaration merging, extension method can be added as below.

interface Date {
    compareDate(date: Date): number;
}

above code defined interface called Date with method name comparedate. So this will merge merge method called compareDate on existing Date type.
But above code just add method declaration without its implementation. Below is code which provide implementation of compareDate method.

Date.prototype.compareDate = function (date: Date) {
    if (this.toLocaleDateString() === date.toLocaleDateString()) {
        console.log('equal');
        return 0;
    }
    else if (this > date) {
        console.log('greater');
        return 1;
    } 
    else if (this < date)
    {
        console.log('less');
        return -1;
    }
}

so once implementation added , compareDate method get added to Date type of typescript and ready use. Below screen

Below is output of compareDate method.


Code to test
var date1 = new Date('4-3-2015');
var date2 = new Date('4-2-2015');

console.log(date1.compareDate(date2));

No comments:

Post a Comment