Array Extension methods - Typescript
This is step by step guide to create custom library for extension method on Javascript Array using Typescript.
Tools and framework we are going to use are
Open Command prompt and type following commands
- mkdir demo-extension-lib
- cd demo-extension-lib
- npm init
Once npm is done with initialization, Open demo-extension-lib in any editor of your choice. We will use Visual Studio Code for our demo.
You will se single file package.json as we do not have any other library install.
We will start by adding two directory src - for source code and test - to add test cases.
Add type script file with name extension.ts. In that file, declare Array interface to global namespace
One thing to notice here we are exporting this module as {}. This interface is basically to extend definition of existing Array. Now that have defined interface, it needs to be implemented. we will define each functionality in same extension file.
Lets implement addRange method.
Here, we first check if addRange method already exist on Array prototype or not. If not then we add addRange definition to Array.prototype. First argument this is to tell compiler that its an extension method to existing JavaScript array. This argument will not appear in method definition when we type dot(.) to any object or type array.
However, second argument is the actual parameter that would be available in function to process. Similarly, we can implement rest of the methods.
Implementation of rest of the methods can be found at my GitHub repo
In Next post we will discuss how we can
- Build library
- Add Unit test cases
- Unit test covergae.
Thank you for Reading!
Comments
Post a Comment