Angular transition to 2.0, part 8 – TypeScript

BrieBug Solutions has created an online video series that provides information, tips, and insight on the transition from Angular 1.x to Angular 2.0. This video is a great resource for those in the industry who are interested in programming, typically programmers, to be aware of the Angular changes, as well as receptive to technology growth.

This video is eigth in our series on how to transition from Angular 1.x controllers/views to Angular 2.0. This video covers converting to TypeScript in preparation for the final push to Angular 2.0.

Today we’re going to continue our series on transitioning to angular 2.0. I’m going to be talking about typescript. So previously we took a hottowel project, John Pappas HotTowel project and we refactored it to use a component-based design. So we moved logic out of controllers and into component directives. If you miss, this the videos are available on YouTube so please go ahead and catch up. Today we’re going to be comparing the JavaScript code, the refactored Hottowel project, JavaScript code to the equivalent typescript codes for angular 1.0. So let’s take a step back for a second.

Why? Why should we bother refactoring our angular 1.0 application at all? Why would we want to use directives over controllers? Why use component-based design? Why use typescript? Why not use ES6? And how does all of this help you get ready for angular 2.0? Well let’s take a quick look at angular 2.0. I think that help answer some questions. Angular 2.0 is a complete rewrite of angularjs and it’s very different. It’s been rewritten from the ground up. It does not have controllers, it does not have scopes and application is not a series of modules that are registered with angular different types.

It is simply a component tree and the code base for angular 2.0 is written entirely in typescript. So why such a drastic change? Angular is six years old and web technologies have evolved a lot since then. When angular was first created it was built to fill a certain need that Google had at the time and it grew and people used in ways that they never imagined it would be used. And as such you know over the years they have tried to improve it. Improve performance, you know patches necessary without breaking it but there’s only so far that they could take it. And you realize that going forward there’s a lot of lessons they learned from angularjs and to really make a top notch web framework they needed to rewrite it and redesign it.

So angular 2.0 is completely different now they can be written in JavaScript in ES5. Using type script or ES7 teachers or call it ES6 plus maybe will result in a much cleaner implementation. Let’s take a look an angularjs example, a very simple application. Here we are registering our application called myapp. We have a factory in my service with the get name function, we have a controller, and my controller in this case that caused that get me and function on the service and populates a scope variable called the name. And then we have a directive that accepts and is actually called name, and plugs it into its template and prints out hello. Hello. you can imagine the HTML, you have an NG app which is equal to my app, you would have a div controller with like a ng controller attribute on it, You would have my controller to find there and then in the scope of that controller you have my desk dir like directive and you plug in the name value from the controller’s scope into that directive and you end up with hello world imprinted on the screen.

So what does this look like an angular 2.0? Well angular 2.0 takes a bit of a different approach. So using regular JavaScript this application can be written into angular 2.0 like this. So you have a service, which is a class that has a getName function on it but returns world. And then you have a component, your app component. So and you define the component like attributes of that you described, you have a selector call myapp, you have to specify that you want to be able to inject my service into this component. your view template right there and then you’d have a class that represents that component which is based in this case is just a simple constructor where you can inject my service, call get name and attach it to the scope. So it’s still nice and clean. A little bit more structured and a little easier to understand and I’ll take a look at the same example using ECMAScript 7.

So again you have a class, my service. Now you can start using the class features that come along with ES6, you have a decorator on that service that describes it as injectable. Then you have a class called my app component, you decorate that with the component decorator where you define the selector. A new decorator you define the template and then again you have that constructor for the component that where you can inject my service in and you can call it. So you can see when you take a look at the JavaScript implementation it’s basically tries to implement the ES7 way of doing it but in a way that works with JavaScript. Since JavaScript currently does not support decorators or classes it has to use the syntax of providing ng class and like ng.u component. So what does typescript bring to the table? Well we’ll take a look at the typescript example and it looks pretty much like the es7 example.

Again you have a class that is a decorator described as injectable. You see a couple minor changes. In this case get name we actually we are actually explicitly defining the type that returns so returns a string value. If we go down a little bit further and my app component we have named to find a string now and you also see we don’t need that at the inject decorator on my service parameter in the constructor anymore. Since typescript is strongly typed angular 2.0 knows that you wanted my second instance of my service and automatically injects that for you. So, but still very similar to the only that’s in angular is that it types.

So es6 and es7 isn’t even out yet so why are we even talking about es7. Well es6 introduces most of the things that are needed to work with angular 2.0. Its classes, modules provides a bunch of other stuff; arrow functions destructuring, promises, iterators, and a whole lot more. A whole lot of neat stuff coming out with es6 but decorators, one of the key parts of angular 2 is not a part of ES6. They are in the es7 proposal. Even when the es7 successfully adopted you’ll still need to use a transpiler, like traceur babel in order to support those decorators. Type script is basically like the website described it as a type superset of JavaScript, compiles to plain JavaScript. So what that means is you can take JavaScript code, you can take a .js file, just change the extension to .ts and typescript world be able to compile it and its totally valid typescript.

So what are some of the features you get with typescript? Well it includes almost all the features of ES6 plus a few additional ones. The big ones being decorators but also includes types, interfaces, abstract classes, generics; really those features associated with strongly typed languages. So what’s the big deal? What does that give you over es6 or es7? You know why would you want to use type script instead of just using es7? Like in a trance pilot? Well it really comes down to the benefit of types and this is also why the angular team went with type script as well. So it ensures type safety when you’re writing your code, so you get no runtime type hours anymore, it allows you to develop my contract and the code is much more explicit and easier to understand. Let’s run through those for a second you think about type safety.

In JavaScript you basically you can pass anything into any functions so even if you write a function expecting a string to be passed in you can pass in an integer and everything will be fine but then at run time if you’re trying to call a function on that parameter they exist for string and what doesn’t exist for an integer then or number then you’re going to get a runtime error and there’s no. these are these are popular I guess I’ll call it that people have in their applications when using JavaScript because it can be hard to make sure that you’re writing the code you write doesn’t like is type say. So it allows you to develop contract.

So what does that mean? Well with types you can define interfaces that’s explicitly define what an object or function or class should look like. So for example of a function that accepts a config object let’s say and this is a popular pattern. Someone passing a config objects and that object contains certain parameters, certain configuration feels. well in JavaScript you have to kind of go take a look at the function and see what fields it’s expecting in order to know that you know in order to know what you need to pass in and if you have a typo or an error in your passing and you won’t know about it until runtime.

Or with interfaces you can actually explicitly say I want an object that has these three fields are required, these two are optional, this is what are you expecting and if you don’t provide something that matches that interface type script at compile time it right away will tell you that you have an error in your code so you don’t have to wait till you get all the way to play it out and someone and have some someone off use case and breaking the operation or application and then finally the code is more explicit and easier to understand. And you know the same example if you know what object you need to pass in, what that object should look like it makes your life easier as a developer. Using like calling someone else’s function.

And the next thing about typescript is it’s very flexible she can still take advantage of JavaScript dynamic typing. and you can use your going to find a type of the string, a number or you know like array but you can also use the any type which basically means that it can accept any value so you can set it to a string value initially and then send it to a number later just like you can in JavaScript. You can also define multiple types that can be accepted by field, so this example we have is enabled them are saying that it can be either Boolean or number. So you can safely set it to a Boolean value like a number like one but if you said that to the string true than you’ll get a complete compile time error from typescript. Let’s go back and take a look at that angularjs 1.1 example.

We’ve broken it up slightly differently so rather than have all of the inline functions we’ve actually broken them into explicit functions and you’ll see why minutes. You can compare it to the same code written in typescript. So again we have a service, we have a controller, we have a directive and we register all of those with angular as part of my app. So if we take a look at that same example and type script you can see it’s really not much different instead of defining a function we’re defining classes so my service instead of being a function is now a class so being a function that returns an object it’s a class that when you call its constructor will generate that same object, so does the same getName function. on my controller again previously so we were attaching things directly to the controller it was a constructor function now it’s a class and the constructor itself is defined within that class and the directive against overturning an object we provide for providing a class with all the fields of the object was previously returned and then angular knows how to handle these classes since they’re really just when this gets compiled them to JavaScript it’s going to look very similar to this JavaScript currently.

It pretty claimed, so not a big not a big jump from angular sorry from JavaScript to typescript. Let’s take a look at some actual texture code out there in the wild. So the first one will look at is the angular 2 code base. I knew I was completely written type script so you can come here take a look at how the angular team has actually created their directives. Use that as a template for your own as you work with angular 2. So let’s go in to take a look actually modules.

Let’s take a look at the ng class directives in angular 2. So here’s what the typescript looks like you’ve got you know like typescript supports modules. So you’re so explicitly pulling in specific functions and classes from a module. Some kids were calling them interfaces so you can define exactly what it is that you need just like, like using require. so now they’re defined their directive here so directive and angular 2 is very similar to a component and angular one you can think of directives as being of two types really; you can have a decorator directive that is an attribute on an HTML tags or decorate that element or you can have a direct of being element itself and have its own HTML template and then go to the they split those off a directive is the equivalent of a decorator directive in angular 1 so it just decorates and it’s the same element and a component has its own view and is essentially elements in angular 1.

Here you specify the selector, it puts you can see your private attributes, one of the nice things about type script is you can maintain you can capsulate data within classes so you’re not exposing it, you can hide that information. with that these private fields if anyone or another type script class tried to access them in touch with throwing arrow, therefore you’re at compile time but those are private person private attributes. You have a constructor these private key words in front of the parameters indicate that these will be assigned to private fields on the class some little shortcut there. We have some setters explicitly set values for fields we have to check in on to destroy some methods on their which actually fulfill as you can see this class implements just do check in on destroying interfaces. So by having these two functions here, we are going to take one of those out type script would say that you’re not implementing the understory like interface number of private helper functions in the class that aren’t exposed outside the class.

Overall you know if you worked with Java or C sharp or any of those languages than this should look very familiar and you get the same benefits as you get from those languages. so that was an angular 2 example. So let’s take a look below at the JavaScript version of the hottowel project that we had refactored previously and the typescript version. We will take a look at what those look like side by side. So here’s the JavaScript one so it’s going to start take a look at a few things.

So if you go to Step 9 that is the completely refactored version of this code base. So and what we based the typescript application off of alright so let’s take a look at the features, portrait or dashboard controller here. So what does that look like in typescript? So in JavaScript which I’m sure most of you are familiar with this structure we are registering the module. Dashboard. We are attaching the controller to the moduleapp.dashboard. the dashboard controller here will specify what we are injecting and then we go in and we assigned values to the scope and you know what fairly straightforward. Let’s take a look at the typescript version of this. little more explicit so when we actually can define what like an interface that says what the model should look like in this case for of you were expecting news object that has a string title most description. We’re expecting a number, message count, we’re expecting a people array and we’re expecting a string title.

And so then our dashboard controller can implement that model to make sure that what gets passed along to the view is actually there, not missing anything. Your constructor function which basically assigns some default values that are passed in and close that logger info. So when we look at the one that happened in the end function before and then we register the controller with angular. So again very similar you know just a little bit different approach here. Let’s look at something else here. Let’s go into components. Take a look at people components, here’s the directive for that. Let’s look at the typescript equivalent.

So in JavaScript we have people directive that we are registering with angular. We have a controller and that directives respect that in not checking anything into and we also have a click event handler here that’s just a window alert. It’s very straightforward we have an isolated scope with a people object on it, a controller, and a controller as bind to controller. So in type script and take a look so we have our people scope so again that’s in like 10 interface defining what the what the scope should look like and then we implement that down here, we define the scope, we have our constructor where are you I’m sorry have an empty constructor but can’t really do anything when we’re creating a new directive and we have this instance function.

We will talk about that in just a minute then returns an instance of the people class. Down here all those same attributes bind to controller is true controlleras vm controller function people controller which is implemented down here. Very similar to what we see here people controller has that click person as we have here click person which was closed the window and then we register this. so one thing worth noting is when you register directive it’s expecting an actual object so in this case rather than returning the people class and injecting people class in here we are injecting an instance of that class so we call where we pass in a function I’m sorry let me clarify when you register a directive what angular is expecting is a function that can call that will return an object instance of that directive. So we’re passing along the function instance which will return an instance of people.so that’s why we keep going but it would look pretty similar across the board so we’ll move on.so converting to type script. So what do you have to do to actually make that conversion?

Well like I mentioned before since type script is a superset of JavaScript first step is just rename your files to dot T S extension and then compile and then getting the typescript compiler to compile them into to dynamically create those Js files. Then you can start refactoring your code. you can start adding types classes interfaces all that stuff almost all major third-party libraries have type definition files and what they do is allow you to pull in a JavaScript library let’s say like he angular library or jQuery or whatnot and know what the interfaces know what types you should be using, to call functions within that library. For more information go to definitelytyped.org later said almost all of the big ones are out there. And they have this typescript definition manager TSD command-line tool which use kind of like mph. and allows you to complete your typescript project and automatically pull in those definition files that you need for your projects.

So really handy really helps you get spun up quickly and actually let’s take a quick look at what that looks like. So look at hello world typescript, let’s go back to the route here. So these are the typing so in in our index HTML for example we pull in jQuery.js. that’s probably what this type definition file does is it basically has the API but you interact with jQuery but it’s completely typed so it’s not a bunch of interfaces so the jQuery example a jQuery settings if you’re just working with jQuery and JavaScript all you know is the settings are an object and you need to look at the documentation to see what fields are there. so what these type definition files provide an actual interface that defines all the types and whatnot so when you’re writing your type script code it will check against these type definition files to make sure that you’re passing in the right values, the right types and whatnot and it can give you that compile time check to make sure you’re using the jQuery library correctly. alright so we’re learning typescript there are the most popular resources that I found for learning typescript, the website is fantastic.

Take a quick look at that. you know they have a simple tutorial that you can step through, kind of a quick introduction, the Handbook goes into a whole bunch of detail you know all the basic types, interfaces and how to use them, examples to go through classes, modules, generics all that stuff really great resource for learning how to use typescript. So what else we have, pluralsight has some excellent classes. Fundamentals taught by John Pappas and Dan wahlin on who is on the typescript team at Microsoft. Typescript, angular with typescript. A great course if you want to learn and a very new on the how to effectively write your angularjs applications using typescript and then john papa has a visual studio code course out here to which is a great idea for using typescript and then edx also has a good in depth courses taught by again by Dan Whalen who’s on the Microsoft typescript team and this is a nice long course and will go into a lot of detail.

These are some of the more popular ones also various tutorials of, like on mine just kind of go out there and find what you want but I’d start with those three, with those three sources. So the other nice thing that typescript provides is the playground so if you go back to the typescript site. if you click on Play up here and it loads up this playground you can load up example code so some examples classes, generics whatnot but the nice thing about this is you can type in your own stuff here and class and you’ll see that as your typing it’s compiling it into JavaScript you can see side-by-side the types your code and the JavaScript equivalent. So great place to play around and really understand how typescript works and what and to understand the language. So some of the major editors out there for typescript, these are probably three most popular.

The visual studio code, if you haven’t used a fantastic it is a beta product right now but one thing Microsoft has done well as historically done well is IDEs. In this case for just your code is not I don’t think I don’t think of it as Visual Studio it is a simple editor but it has some of those things that you love like intellisence. They have some of the best like auto complete functionality in the business. And visual studio code, since its Microsoft developed this and typescript as a Microsoft product that has fantastic support for typescript. Sublime text also has some plugins that will support type script and web storm as well I believe supports it out of the box. So these are the three most popular ones and that’s all we’ve got for you today so again type script is going to be a big part of angular 2.0 and a big part of writing effective applications in angular 2.

So learning it now will help you when Angular 2.0 is released. And well converting angular 1 apps or building new ones using typescript will help you make that migration later so thanks for joining us today. Stay tuned our next one we will actually start diving into angular 2 so you start to see why we took some of these initial steps and we’ll look at converting this hottowel project into angular 2.0. Thank you for joining us.

Please enjoy, learn, subscribe, and like our channel on YouTube.

We would love to hear from you so don’t hesitate to share your ideas or provide us with constructive feedback.

BrieBug Solutions a Denver based website and mobile application development agency that specializes in Angular and Full Stack development. If this is a technology that you would be interested in to boost your business, feel free to contact us so we can get you started on your vision!

  • Contact Us
  • Telephone: 888.679.2201
  • Address:
    BrieBug |
    12596 W Bayaud Ave Suite 201 | Lakewood, CO 80228