Community Post

TypeScript: Should I be using it?

Max Hershey

In this post, we will investigate why TypeScript could be the transpiler for you.

For helpful resources regarding ECMAScript 6, check out this GitHub repo.

If you are new to TypeScript and not sure what it is, head on over to Peleke's post: Why You Shouldn’t Be Scared of TypeScript. He does an excellent job of describing what TypeScript is compared to some of its competitors.

A need for ES6+ Transpilers

It's 2017, and the web's ever-expanding amount of technology is bigger than ever before. Naturally as web developers, we want to use the latest and greatest technologies possible. There is one problem, however, that has plagued us since the dawn of the web: cross-browser compatibility. Unfortunately, not all browsers support the latest standards from ECMAScript 6 or beyond. Then came the transpilers. They allow us to use the new and exciting features, and then transform or compile our code into an acceptable format for modern browsers. The question is: which transpiler will you choose?

Why choose TypesScript

Babel is still one of the most popular and widely used ES6+ transpilers on the market. It is an excellent choice for JavaScript developers looking to expand their code with ES6+ features. Also, TypeScript was created by Microsoft, who has a reputation of forcing developers to stay in the Microsoft ecosystem of development tools and environments. Yuck. These facts alone will generally scare off any new front-end developers from choosing TypeScript as their transpiler. I'm going to tell you why, despite the facts, TypeScript might be the best transpiler for you.

1. Microsoft, and C-based languages

As mentioned above, locking yourself in the Microsoft ecosystem can scare away many developers. However, if you are already a part of that ecosystem, TypeScript is a dream come true. If you, like myself, come from a background in ASP.NET development, or any kind of C development, then JavaScript may at first be a painstaking language to learn. JavaScript has several common pesky errors, like undefined is not a function; and then, there are things like this:

console.log(9999999999999999 == 10000000000000000); // evaluates to `true`
// Don't believe me? Press F12 right now and paste that into your console. 

The bottom line is this: If you are a full-stack developer using ASP.NET server side, or come from a background with strongly typed programming languages in general, writing vanilla JavaScript can be difficult. If C# and JavaScript had a baby, it would be TypeScript. TypeScript can provide training wheels, so-to-speak, to make writing JavaScript easier for type lovers. Let's say you want to write a function that adds two variables together. In vanilla JavaScript our code would look something like this:

function add(a, b) {
    return a + b;
}

var c = add(1, 2);
console.log(c); // evaluates to 3

Simple enough, right? Looking at this function at face value, a few assumptions are made:

  1. This method always returns the type number.
  2. Both parameters a and b would always be passed in with a type of number. However, we cannot always guarantee this. add may be called from markup, or another developer may be using add incorrectly somewhere else in the code base. You might end up with something like this:
var a = '1',
    b = 2;

var c = add(a, b);
console.log(c); // evaluatues to `"12"`

Now we have some serious problems! Our code expected the number 3 to be returned, but not only did it return 12, its a string. When using the + operator in JavaScript, if one of the parameters is a string, it will concatenate the characters and return a string. Only if both ends of the + operator are numbers will it add them together.

It is errors like these that us type-loving developers hate about JavaScript. In TypeScript, this wouldn't even make it past the compiler. Let's see this same function in TypeScript:

function add(a: number, b: number): number {
    return a + b;
}

var a = '1',
    b = 2;

var c = add(a, b); // compiler error: [ts] Argument of type '"1"' is not assignable to parameter of type 'number'.

// -- or --
var a = 1,
    b = 2;
var c: string = add(a, b); // compiler error: [ts] Type 'number' is not assignable to type 'string'.

Imagine all of the headaches cured from just this example alone by adding simple type saftey to JavaScript. In our example above, we typed the variable c as a string, but left a and b un-typed. One of the great benefits to TypeScript, is it is a super set of JavaScript. What that means is that you can write all of the vanilla JavaScript you want in a TypeScript file, and the compiler will accept it.

This example alone was enough to sell me on TypeScript, but there is more.

2. Angular

Angular has grown to be a leading JavaScript framework in web applications today. Which transpiler did the Angular team at Google choose for Angular? You guessed it: TypeScript. In Fact, Google chose to scrap their own AtScript in favor of using TypeScript. Because of this, TypeScript's community instantly gained the community base from Angular. This is a huge benefit. A larger community base, fueled by Google developers means more content on websites, such as this post, more TypeScript questions and answers on Stack Overflow, more developers finding and fixing bugs, and the list goes on and on.

3. Enhanced IDE support

Your development experience using TypeScript is a great improvement over plain JavaScript. The IDE or text editor is informed in real-time, by the TypeScript compiler, of all errors present in your typed code; this gives a few major advantages. For example, with TypeScript, you can safely do refactorings like renames across your entire codebase. You can use common features like Find all References or Go to Definition. Through code completion you can get inline help on whatever functions a library might offer. No more is there a need to remember them or look them up in online references (for more see DefinitelyTyped). Compilation errors are reported directly in the IDE with the typical red squiggly line. Here are the IDEs / Text Editors that support these amazing features: More than likely, your editor of choice is in the list above. With TypeScript, you can enjoy writing code more, and debugging errors less.

4. Interfaces

Tell me if you have ever been here before:

function print(user) {
    console.log(user.PersonID); // undefined... not it.
    console.log(user.personID); // undefined... still not it.
    console.log(user.PersonId); // undefined... :'(
    console.log(user.personId); // undefined... C'MON!
    console.log(user.personid); // 123... Finally! :)
}

If you have, you are not alone. TypeScript offers us the ability to create Interfaces. Interfaces are not new to us; plenty of languages like C# feature Interfaces out of the gate. Interfaces allow us to set a contract that all objects inherting from a given interface MUST hold to. Let's see an Interface in action:

interface IUser {
    personid: number;
}

function print(user: IUser) {
    // we know in real-time that `personid` is a required property of the `user` object.
    console.log(user.personid); // 123
    // in fact, trying to use anything else will throw a compiler error.
}

Interfaces give us type safety on our objects, so we never again need to wonder what we named that one property, or what properties we have available on an object; it is all just right there in the intellisense of our IDE or Text Editor. We also have the option to mark properties as optional or read-only. We can also specify what a constructor should take for any class that inherits from a given interface. TypeScript's Interfaces give us the ultimate flexibility in the amount of type safety we want to use it. Using Interfaces properly also gives us a practical principle that is extremely important in larger applications: scalability. Do you want to refactor tons of code that interacts with our IUser interface from earlier? Simply change the interface and instantly know all the places your code needs to change. Adding a new developer to a six-month old project? They can join the project knowing in real-time how to interact with any IUser object. This is a huge benefit that will become more and more apparent as you increasingly use Interfaces.

5. ES7 and Beyond!

ES6 still isn't fully supported by modern browsers yet. Is it wrong to think about ES7 and the future of JavaScript standards? Of course not! TypeScript already has support for several ES7 features, and it will continue to be developed on a path that parallels the common web developer's desire to use the freshest technologies available. A prime example of this is Decorators. A Decorator is defined as an expression which returns function and can take a target, name, and property descriptor as arguments. You apply it by prefixing the decorator with an @ character and placing this at the very top of what you are trying to decorate. Decorators can be defined for either a class or property. If you have begun using Angular since its 2.0 release, you no doubt have seen or used decorators already. Let's look at a simple controller in Angular:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `<h1>Hello {{name}}</h1>`
})
export class AppComponent { name = 'Angular'; }

Here, the @Component decorator provides metadata that defines something about the class AppComponent. In Angular's case, the @Component is going to define how the AppComponent class will interact with the given template. To learn more about Decorators, check out the TypeScript handbook. TypeScript is here to stay. It will continue to grow in features and functionality that will put you, the developer, one step ahead.

In Conclusion

So to recap, if you are used to having strong types, or are new to JavaScript, TypeScript can ease you into the aches and pains of learning the loosly typed declarations of vanilla JavaScript. On top of that, one of the best JavaScript frameworks ever, developed by some of Google’s top engineers, chose TypeScript as their transpiler. So if TypeScript is your transpiler of choice, you will be accepted as part of a large, growing community of front-end developers. Also, TypeScript is here to stay. Aiding in making web applications scalable today, and looking to the future of what lies ahead for the web, TypeScript will continue to make your life as a web developer easier.

Where do I start?

If you are sold on TypeScript and want to get started immediatly, head on over to website: https://www.typescriptlang.org/. They have excellent documentation to help you get started, including simple installation and beginner tutorials.

Feel free to comment below your likes and dislikes of TypeScript, or if you enjoy using it as much as I do.