Ionic and TypeScript sitting in a tree
So, TypeScript is the all new thing that allows you to use features from ES6 (or ES2015), ES7 and beyond. Say goodbye to loosely typed variables and say hello to modules, classes, interfaces and so much more.
In order to use TypeScript in an Ionic Framework project there are a few small things you need to do to get things running.
1. Install and configure the gulp package
- Install the gulp-tsc package and save it to the development dependencies in
- Next, require the package in your gulpfile.js like so
Add the following line to the paths object:
Add our compile task
- Add our task to watch
- Now change the ionic.project file and add the compile task to the gulpStartupTasks. If the gulpStartupTasks section is not present at all, just add it anyway.
2. Add TSD
TSD is a TypeScript Definition manager for DefinitelyTyped. TypeScript used TypeScript Definition files so it knows how to handle the TypeScript you are writing and gives you intellisense. Let’s install TSD so we can continue.
This will create a typings folder which contains a tsd.d.ts file with references to the typings needed for ionic and cordova. In the root of your project a tsd.json file will be created with all the installed definitions. All you need to do to use the typings in your TypeScript file is include it at the top like so:
3. Prevent editor from compiling on save
Now to prevent your editor to auto compile TypeScript we add a tsconfig.json file to the src folder with this in it:
4. Add TypeScript files in src folder
Now that we have everything set up it’s time to start refactoring your application.
Of course don’t forget to add the reference on top of your files to the tsd.d.ts file in the typings folder.
If you now run
ionic serve, you should see a message that looks like this one.
“Compiling TypeScript files using tsc version x.x.x”.
TypeScript will process these files and write ES5 files to the www folder.
As you can see it is fairly simple - just 4 steps - to add TypeScript support to your Ionic project by changing the default gulp setup used by Ionic.
It’s nice to know that Ionic 2 will have support for TypeScript built in so you won’t have to do it yourself.
By adding a flag
--ts to your Ionic 2 project setup it will be enabled.
Personally I love using TypeScript and will use it whenever I can. It makes my life as a developer a lot easier by spotting errors before I even hit the browser.
What are your thoughts about TypeScript? Feel free to add them in the comments section.