Why Static Typing & Why is TypeScript so popular?

According to the Stack Overflow Developer Survey 2020, 67.1% of TypeScript users loved it. This makes it the second most loved language, behind Rust, and narrowly beating out Python. JavaScript was number 10, with 58.3% of users interested in continuing to use it. That is still pretty good. It sure beats Visual Basic. But why is TypeScript so much more popular?

TypeScript 4.0 will probably be released before this article is published. Now is a good time to talk about it.

1. What’s a TypeScript?

TypeScript is much like JavaScript. In fact, all JavaScript is valid as TypeScript code. TypeScript was developed by Microsoft to make it easier to write large code bases. Essentially, it’s just JavaScript, with static typing. The TypeScript compiler does nothing but convert all the TypeScript code into JavaScript. The resulting JavaScript code can be run in any browser.

`1.1. What’s Static Typing?

If you don’t know, static typing is when the compiler enforces that values use the same type. Here’s an example. This is valid in JavaScript:

let value = 5;
value = "hello";

Here, the type of value changes from a number to a string. In TypeScript, this is forbidden.

let value = 5;
value = "hello"; // error: Type '"hello"' is not assignable to type 'number'.

2. Why TypeScript?

Why would you use static typing? Most of the time, it’s for performance reasons. As explained in the low level JavaScript article, there is a performance benefit to letting the compiler know what type the value is, without having to check it.

This isn’t the reason to use TypeScript though. Alas, TypeScript doesn’t take advantage of this. The real benefit to using TypeScript is to prevent certain glitches.

There’s one famous example of JavaScript being weird. If a program inputs a number, and the user inputs a string, you might try to do some arithmetic on it.

// userInput = "2"
console.log(userInput + 2);

You may expect the console to print “4”, but JavaScript doesn’t do this. Instead, it gives you, “22”. Because userInput is a string, adding a number to it will convert the number to a string. JavaScript politely concatenates the two strings together, and the result is “22”.

If you use JavaScript, you’re not likely to know what the type for some object is. It’s possible you won’t realize what methods a certain object has, or even what fields it has. It will run just fine, until you need to use the result of that property, causing a semantic error.

class ExampleClass {

    private value;

    constructor(value) {
        this.value = value;
    }

    getNumber() {
        return this.value;
    }
}

let object = new ExampleClass(5);
console.log(object.number); // prints "undefined"

TypeScript knows better. It will give you a compiler error. That means you’ll know the error is there before you even run the program. The compiler tells you what the problem is, so you don’t need to try to hunt it down. A few seconds of specifying types will save you from an hour of debugging.

class ExampleClass {

    private value: number;

    constructor(value: number) {
        this.value = value;
    }

    getNumber(): number {
        return this.value;
    }
}

let object = new ExampleClass(5);
console.log(object.number); // compiler error: Property 'number' does not exist on type 'ExampleClass'

There are other, hilarious examples of JavaScript being weird (and also Ruby).

3. Other Features of TypeScript

3.1. Enums

Yes, JavaScript can do it too, but it’s a weird workaround. TypeScript uses syntactical sugar to make it work much better.

// typescript version
enum Color {
  Red,
  Green,
  Blue,
}

let c: Color = Color.Green;

// javascript version

var Color = {
    Red: 0,
    Green: 1,
    Blue: 2,
}

var c = Color.Green;
c = 6839; // this is completely valid, which kinda defeats the purpose

3.2. Interfaces

You can enforce that a class has certain functions (or properties) by using interfaces.

interface Animal {
    speak(): void;
}

class Dog implements Animal {
    speak(): void {
        console.log("woof");
    }
}

// lots of other things can implement interfaces too, including functions

interface SearchFunction<T> {
    (list: Array<T>, value: T): number;
}

let linearSearchForNumber: SearchFunction<number> = function(list, value): number {
    for (let i = 0; i < list.length; i++) {
        if (list[i] == value) {
            return i;
        }
    }
    return -1;
};

3.3. Literal Types

These are like enums, but slightly cooler.

type DiceRoll = 1 | 2 | 3 | 4 | 5 | 6; // this is a type alias, set to a literal type

function rollDice(): DiceRoll {
    return (Math.floor(Math.random() * 5)) + 1 as DiceRoll;
}

There are more advanced features too. The TypeScript Handbook Reference can be a fun read.

4. Cons of TypeScript

TypeScript isn’t exactly plug-and-play. Node.js doesn’t support it, nor do any Internet browsers. To use it, you’ll need to compile it to JavaScript. To compile it, you can use the program, tsc. If you forget to compile it, then nothing will change and you’ll be very confused.

There are solutions to this. You can use the --watch option on tsc to have your code compile automatically. You can also use Deno. Deno is an alternative to Node.js, created by the same person who created Node.js. Deno can run Typescript natively, so there’s no need to compile it. Deno also has other features, such as security.

The downside of Deno is that Node.js has more support. Node.js has tons and tons of libraries (to the point of insanity), and used much more often. Deno is cool, but you should definitely also know Node.js before going into a job interview.

A lot of jobs also like to use TypeScript, so it’s good to learn it anyway.

Speaking of which…

5. Get Started with TypeScript

A TypeScript cheat sheet is outside the scope of this article. There are already some really good cheatsheets. To prevent this from becoming a master’s thesis, the TypeScript Handbook is a recommended reading. TypeScript can be super useful for preventing type errors. Give it a try, and hopefully you’ll come to enjoy it.

Related posts:

API Authentication with Node.js
How to Build a Static site with Gatsby.js
Building a RESTful Web API in Node.js using PostgresSQL and Express
How To Build A CLI Tool With Node.js And PhantomJS
Breaking Down MEAN vs MERN Stacks
Getting Started with Node.js Event Emitter
How to Use Modular Patterns in Node.js
Understanding HTTP Requests in Node.js
Debugging a Node.Js app using Chrome Dev Tools
Introduction to Sequelize ORM for Node.js
Rendering HTML Pages as an HTTP Server Response Using Node.js
A Deep Dive Into Eleventy Static Site Generator
Building a Websocket Powered Tic-Tac-Toe Game with Adonis.js
Linting in Node.js using ESLint
Building A Room Detector For IoT Devices On Mac OS
Writing A Multiplayer Text Adventure Engine In Node.js: Game Engine Server Design (Part 2)
Implementing Lipa na Mpesa Online using Node.js
Implementing Secret Key Cryptography in JavaScript
Getting Started with Node.js Paypal Checkout Integration
Getting Started with Strapi API CMS
Useful Node.js Tools, Tutorials And Resources
Uploading Files using Formidable in a Node.js Application
Open-source packages & Code Security using NPM
Node.js Structural Comparisons
Creating Node.js Application Using Express Generator
Why Node.js is Good for Online Stores
How to Generate QR Code Using Node.js
Developing A Chatbot Using Microsoft’s Bot Framework, LUIS And Node.js
Session Management in Node.js using ExpressJS and Express Session
Building your First Telegram Bot using Node.js and Telegraf
Node.js Firebase
How to Set up a Node.js Express Server for React