Angular Developer: JavaScript to TypeScript

Chris Shatrov Angular, JavaScript, React, TypeScript 1 Comment

Attention: The following article was published over 6 years ago, and the information provided may be aged or outdated. Please keep that in mind as you read the post.

New JavaScript frameworks and libraries are created every day. This generates a dilemma: which solution should we use when starting a project?

My web development experience over the last few years has mainly included the AngularJS and Backbone.js frameworks. Angular, jQuery and traditional JavaScript have been in my comfort zone. When I ended up being face-to-face with TypeScript, it felt new, scary, and pretty confusing. I want to make that transition easier for you!

The goal of this post is to provide you an understanding of TypeScript, particularly when you come from an Angular web development background. To do so, we will first give an introduction to TypeScript. We will then discuss the differences between the different versions of Angular & Angular vs. React, with an eye for what you need to know to understand the JavaScript tooling landscape TypeScript plays in. And, lastly, we’ll go through a tangible TypeScript example for a look into syntax & structure.

Part 1: Introduction to TypeScript

What is TS?

TypeScript is a free and open-source programming language developed and maintained by Microsoft. It is a strict syntactical superset of JavaScript, and adds optional static typing to the language. Also check out some other publications we’ve written, like Introduction to TypeScript or Converting Enterprise Applications to TypeScript.

How does TS compare to JS?

TS has gained a lot of popularity since the Angular 2 project decided to adopt it. TypeScript does something similar to what LESS or SASS does for CSS. They are super sets of it, which means that every JS code you write is valid TypeScript code. Also you can use the other add-ons to the language, and the code will be valid JavaScript. You can even set the JS version that you want your resulting code on.

Using TypeScript can help avoid painful bugs people commonly run into when writing JavaScript by type-checking your code. TypeScript can actually report issues without you even saving your file, and leverage the type system to help you write code even faster. (Which leads to a truly awesome editing experience.)

However, it’s quicker to set up something in JavaScript. The lack of a type system makes for agility and ease of changing stuff. But it also makes it easier to break things. JavaScript is more flexible. You have to remember that the main purpose for a type system is to make it hard to break stuff. If TypeScript is Windows, JavaScript is Linux.

As it was already said, TypeScript is a superset of JavaScript. This means that you can easily convert JavaScript to TypeScript later if you need to.

Why do we even use TypeScript?

TypeScript brings several new features to the table. The most notable of these are classes, interfaces, and compile-time type checks.

It is better to use TypeScript when:

  • You have a large codebase. When more than one person works on a project and the code base is huge, TS will help you avoid common errors.
  • Your developers come from strongly typed languages. When developers are already experienced with languages such as C++ and Java and don’t want to deal with just JavaScript.
  • A framework recommends using TS. Such as Angular 2+.
  • You really need that faster performance.

Part 2: AngularJS vs Angular 2, 4, 5

So what is the deal with all of these version numbers? What is Angular JS, Angular 2 and Angular 4?

  • Angular JS was released in 2010 by Google. It became popular very quickly because of its feature set. Different versions of Angular JS were released like – 1.1, 1.2, and so on.
  • Few years later, Google engineers completely rewrote the framework to match the needs of today’s rich client-side applications. They created a new version of Angular JS in TypeScript (which is not backward compatible) and released Angular 2 as a framework in 2016. They named it as Angular 2, removing the .js suffix.
  • Few months later after the release of Angular 2, new features were introduced and various bug fixes were done and the new version was released as Angular 4. There is No Angular 3.
  • What happened to Angular 3? Angular codebase is broken into parts/libraries such as core, compiler, animations, router etc. Each of them can have their own version. Router library reached version 3 and others were still at 2.3. Next version would be 2.4 but having version 2.4 for the router library is incorrect – so to avoid confusion they skipped version 3 and Angular 4 is released.

So when we say Angular it means Angular (2+). When when we say AngularJS, it means Angular JS(1+). See the Angular product website here.

Part 3: Angular vs. React

AngularJS and Angular2 / 5 are very different; even an experienced AngularJS user may get confused. But what ReactJS, another very popular one? How do those two compare?

Angular 2 can give you more facilities than React. It can give you more options of doing things in JavaScript frameworks with the enhanced dependency injection and services.

React is a library designed to solve UI issues. This makes its size smaller than Angular and also simpler, so its learning curve is fast. One of its differentials is the ability to use JSX, though it is not required. JSX is a very important element that contributes to the easy declaration and creation of components.

However, using JSX means that there is no HTML. Therefore, those configurations that are natural in HTML, like styles (CSS), add some more concepts to learn. Also, since there is no clear separation of concerns (JS and HTML), as everything is in the JSX, the designers who don’t have development skills may need the help of a developer to organize their work, files, CSS, etc.

First of all, you have to understand that React is a library while Angular 2/5 is a framework. When we use React, we will surely need to use other tools to accomplish many of the tasks we need.

  • React allows us to select the set of tools from which to work with from several options while Angular already comes with all that we are going to need, integrated into the framework. This difference plays in favor of React if this freedom is seen as something positive. But it can also play in favor of angular because that freedom that React bring us can make it very difficult to make decisions about what to use, what not to use and why.
  • Angular 5 has an HTML-centered design, while React has a JavaScript-centered design. This can make Angular a bit more complex to understand.
  • Angular 5 has learned a lot from Angular 1 and from React; this has made them adopt some of the best features of both technologies.
  • Although Angular 5 has greatly improved its performance with respect to Angular 1, React is still higher-performing, faster, makes better use of memory, and is easier to use.

The decision between React and Angular 2 is not easy, and there is probably no single answer or truth. There will be obvious differences between the “fans” of one world and the other.

I say, if the team has no experience in any technology, perhaps the best option would to use React. It will require learning some other frameworks and complementary libraries. But thanks to the simplicity of this library, it will require less time than Angular to be productive and achieve good results with levels of high quality.

Part 4: Let’s Get Started: Angular 2 / 5 and TypeScript

For me, the hardest thing was to switch between Angular 1 & Angular 2/5. My brain just tends to work that way. Once I am very comfortable with something, I have a difficult time switching to something new and learning to understand it. So let’s talk about basics of TypeScript and how Angular 5 works and utilizes it.

Syntax

One of the things that confused me the most was syntax. Since, I am mainly targeting folks who already have experience in Angular 1, let’s jump right in and let me show how things are done in TypeScript.

There are 3 basic types in TypeScript:

 let confirmed: boolean = false;
 let totalTasks: number = 42;
 let employeeFirstName: string = "Chris";

But, you can omit the type annotation if the variables are derived from explicit literals.

let confirmed = false;
let totalTasks = 42;
let employeeFirstName = "Chris";

When it’s impossible to know, there is the “Any” type.

let notReallySure: any = 4;
notReallySure = "maybe a string";
notReallySure = false; // now boolean

For collections, there are typed arrays and generic arrays.

let list: Array<number> = [1, 2, 3];

Enumerations

enum Cars { Ford, Chevy, GMC };
let c: Cars = Cars.Ford;

Now – functions. Functions are first-class citizens, support the lambda “fat arrow” syntax and use type inference.

let f1 = function (i: number): number { return i * i; }

Interfaces are structural; anything that has the properties is compliant with the interface.

interface Car {
  brand: string;
  // Optional properties, marked with a "?"
  type?: string;
  // And of course functions
  move(): void; 
}

Now an object that implements the Car interface can be treated as a Car since it has the name and move properties:

let newCar: Car = { brand: "Chevy", type: “SUV”, move: () => { } };

There is a lot more to TypeScript, of course. But these are fundamental basics that will help you understand some of the difference between JS and TS.

Now let’s move back to Angular 2/5, and actually get started.

For making quick Angular development, we will use Angular CLI. (Before you start to install Angular CLI, make sure you have installed the latest Node.js in your machine.)

  • Install NodeJS. https://nodejs.org/en/download/
  • Install Angular CLI. Go to Terminal and run npm install -g @angular/cli
  • Now we can create a new Angular project using the following command (we use ng to access Angular CLI): ng new hello-world.
  • Now head over to the project directory. cd hello-world
  • And do npm install.
  • And then run it with ng serve. Last command compiles our application and hosts it on a lightweight server.
  • Now open up your browser and go: http://localhost:4200.
  • Congrats!

Structure

Now, let’s talk about the structure of the project.

Your app lives in the src folder. All Angular components, templates, styles, images, and anything else your application needs go here. Any files outside of this folder are meant to support building your app.

  • App: app directory is where we define the building blocks of our Angular project like modules, components, services etc.
  • Assets: as the name suggests, this directory contains all the static assets of our app like images, etc.
  • Environments: the environments directory holds our environment-specific settings, e.g. different configuration files for development, testing, staging, etc.

Files

Now onto the files.

Most of us know what the index.html file is. For those who do not, it is the landing page or the main page of our application and this is where our Angular app Bootstraps.

main.ts file is the main TypeScript file which is used to Bootstrap the Angular module. The check for environment is also performed here as shown in the following code snippet.

AppModule class is imported from the app.module.ts file in the app directory. As I said before, this is where we place the building blocks of our Angular app including modules, components, component styles, component templates, services, and so on.

Now let’s take a look at that app.module.ts file. Here we declare our Angular module, the @NgModule decorator is used to initialize different aspects of the Angular app. Observe that AppComponent is also declared. (See below)

When app.components.ts file simply defines an Angular component, this is where we have defined our app-root selector also (see below).

And finally app.component.html. This is the template file for our app component and this represents the visual part of our component which is rendered in the browser.

So now we know that all the visual components that we saw in the browser in the last part actually came from our app.component.html template.

Part 5: Conclusion

All in all, whether you use TypeScript or not, it doesn’t hurt to try it out in order to develop your own opinions on it. It has a learning curve, but if you already know JavaScript, it will go pretty smoothly. Angular went through a good amount of transition from Angular 1.x, MV* model, to the framework we know today.

The purpose of the transition is to effectively support new features in JavaScript, as well as sync up with the latest web development standards. When used with TypeScript, it is on steroids with support for types, integration with IDE like Visual Studio Code, and many other useful features.

In the process, Angular 1 to 2 upgrade included many breaking changes. However, upgrading to future versions of Angular are expected to be smooth with minimal or no breaking changes. The Angular framework will continue to evolve to support more features and make the developer’s job easy.

0 0 votes
Article Rating
Subscribe
Notify of
guest

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments