How to create a Node module in TypeScript
By Ross Huggett, Developer at Design Pandr
Let’s use the good old Mars Rover kata, albeit, stripped down.
Create a directory for your module and initialise it as a Node module.
The next two commands install TypeScript and Typings globally. Typings is the TypeScript definition manager which installs TypeScript definitions. So in my case, I’m using Jasmine for my tests, so when I come to write my tests, I can write them in TypeScript while still using Jasmine functions like ‘describe’.
npm install -g typescript
npm install -g typings
npm install -g jasmine
These commands are similar to npm in that they define in a typings.json file the TypeScript definitions the module will use.
typings install dt~node --global --save
typings install dt~jasmine --global --save-dev
The next file you’re going to need is tsconfig.json which configures the TypeScript compiler and root files. I couldn’t figure out if there’s a way to generate this on the command line, so I used my IDE WebStorm to generate it for me, but you could just use the example on the TypeScript website. If you just wanted to get something up and running, you could just use mine:
Now install the dependencies.
You should get a new folder called ‘typings’ with Node and Jasmine definitions in it. You’re now ready to begin development of you module.
Create a test in the spec folder. I’ll call mine ‘MarsRoverSpec.ts’, noting the ‘.ts’ file extension and write your tests and implementation in TypeScript. My implementation will be called ‘MarsRover.ts’.
To build the project, just type:
That’s it. I hope you found that useful.
Static type checking made a big difference during development, making refactoring easier. However, there was a clear performance hit.
I had already done this kata before in Java so I had some idea of what it might look like, but I wanted to come into it with a new perspective. Here’s what my implementation looked like in the end.
You can see the full version here, with tests.