Using TypeScript with Angular 1
24th December 2016
TypeScript is the official language of Angular 2, but it is still too early to use Angular 2 in production for many reasons (the most important reason being that it is still in alpha). What if you want to use TypeScript now, right away, without having to wait for the arrival of the stable version of Angular? Well, it turns out that this is quite easy to achieve.
If you are not sure why one would want to use TypeScript check out my previous article – Why you should use TypeScript for your next project.
Creating the sample app
First, we need to create a sample Angular project that we can turn into TypeScript. You can skip this part if you already have a project that you want to experiment with. We will do that by cloning the angular-seed repository made by the Angular team, since it is the easiest option.
You can check that everything is working by going to http://localhost:8000/app/index.html. Now we have a sample Angular that we can work with.
Adding TypeScript support
Now that we have our sample app, we need to install the TypeScript compiler and TypeScript definition manager if you don’t have them installed yet.
We are all set now. The only thing left to do is set up TypeScript compiler for watching our source files and compile them if anything changes. This is easily done by creating a tsconfig.json file in the root of our project:
Changing any TypeScript files will trigger compilation from now on.
Converting to TypeScript
And the TypeScript version:
This is, of course, a very simple controller and it can be improved by making it into a class and then providing it to the Angular, but this is out of scope of this article.
Let us reiterate what we just achieved.
- We created a simple Angular 1 application.
- We installed TypeScript compiler (tsc) and definition manager (tsd).
- TypeScript compilation happens automatically when files change.
- View1Ctrl is now written using TypeScript.
You can now try making your own controllers and converting the remaining code into TypeScript. The complete source code for this article can be found here. Note that node dependencies are not included in the source, so you should run npm install to download them.
Filed under Development