How To Get Started With Typescript?

Photo by Thalia Tran on Unsplash

How To Get Started With Typescript?

Mukhammadyusuf Abdurakhimov's photo
Mukhammadyusuf Abdurakhimov
·Apr 11, 2022·

6 min read

Subscribe to my newsletter and never miss my upcoming articles

One of the most significant innovations in web development in the past decade has been the shift towards Typescript. Learning Typescript is becoming increasingly important for securing a job as a web developer as more companies try to reduce their tech debt.

While dynamically-typed languages make life easier for developers in the short term, they can also lead to unintended problems that aren't discovered until runtime. With the help of TypeScript, we can avoid this issue. Let's look at it more closely.

What is TypeScript?

TypeScript is a superset of JavaScript, to put it simply. This means that while traditional JavaScript code will operate in TypeScript, it will also include a set of additional capabilities that will make our code cleaner and more efficient. To check for faults in the code, TypeScript utilizes a compiler called tsc, which generates (officially known as emitting) the JavaScript counterpart for use in web applications.

TypeScript can be thought of as a statically typed version of Javascript, but it would be overlooking a slew of other benefits. We'll look at some of the benefits of utilizing TypeScript in the next section.

Advantages of using TypeScript

TypeScript has the following features to offer:

Strong typing - TypeScript places a lot of emphasis on the type of variables being used in the code. If the variable is assigned a value that doesn’t match the type, the TypeScript compiler tsc shows an error.

Object-oriented features - TypeScript introduces a whole lot of object-oriented concepts that help make the code easier to manage.

Compile-time errors - Since there is a compilation step involved, most of the errors get caught at compile time instead of run time.

Emitting with errors - TypeScript will inform the developer about the potential errors in the code but it will make sure to generate the equivalent JavaScript to keep the development process running. The final decision is up to the developer.

Great tooling - TypeScript provides access to a lot of great tools which help in editing, error checking, etc. as you type your code.

Let’s take a look at how we can do that with this simple demo that highlights a few of the above-mentioned features as well.

How to use TypeScript

Let's go over the basic building elements of TypeScript before going on to the main example and looking at a scenario that's similar to real-world applications.

The Primitives

The usual JavaScript primitives number, string, and boolean are present here as well. In addition, you can do type annotation to fix the type of the variable at the time of declaration. TypeScript also infers the type when the variable is already defined. TypeScript also has a special type called any which is used to avoid type checking errors on a particular variable.

let message: string = "Hello World"; // string type variable

let myNum: number = 42; // number type variable

let isReal: boolean =  true; // boolean type variable

let special: any = "Any type"; // any type variable

special = 13;  // any type doesn't cause any type checking errors

Functions & Objects

Functions also follow a similar pattern for type annotation where the parameter types are mentioned the same as for regular variables while the return type is mentioned between the parentheses and curly braces. Anonymous functions use a TypeScript feature called contextual typing where the type is inferred from the context of the function usage.

Objects are almost the same as JavaScript except for the fact that the types get inferred for every property inside it. Accessing properties that don’t exist gives a compiler error. TypeScript gives us the option of creating objects using type aliases (cannot be extended) or interface(can be extended).

//This function takes two string types as input and returns a string output

function greeting(firstName: string, lastName: string): string {
    return firstName + lastName
}

let fullName = greeting("Han", "Solo")

console.log(fullName)

// Anonymous functions

// Inferred type
const names = ["Stark", "Potts", "Parker"];

// Contextual typing for arrow functions
names.forEach((s) => {
    console.log(s.toUpperCase());
});

Types on top of JavaScript

TypeScript adds some of its own types as well.

  • Tuples are arrays that have their element types already annotated so we cannot save any other type on that location.

  • Enum’s involve giving human-readable identifiers to numbers/strings. This makes it easier to manage code and avoid the hassle of memorizing fixed values.

  • Unions allow you to use the same variable with multiple types of data without worrying about type errors. This is achieved by annotating multiple types on the same variable using the pipe(|) symbol.

// Tuples -  Special Arrays with fixed type elements

const universe: [number, string] = [1, "Marvel"];

// Enum type

enum Seasons { SUMMER, WINTER, SPRING, AUTUMN };

// can be accessed as

console.log(Seasons.WINTER)

// Unions

let data:(number | string) = 99;

data = "ninety nine"    //valid because it is a union

Using Typescript in a Project

Since we are now familiar with the basic blocks of TypeScript, let’s build a small application and see how we can use it to write better code. This application will take two numbers as input and log their sum onto the browser console.

  1. Before we create the demo we need to set up TypeScript on our machine. Follow the instructions below to set up TypeScript on your machine.

Download TypeScript: typescriptlang.org/download

  1. Create two files index.html and app.ts. Make sure to call app.js inside the HTML file. We will use the app.ts to emit the app.js file for use in the browser environment.

  2. Create the index.html as shown below. This file will contain two inputs for numbers and one add button. We will log the sum of the two numbers onto the console.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TypeScript Demo</title>
</head>
<body>
    <h1>Intro to TypeScript</h1>
    <p>Remember to open the browser console</p>
    <button id="add-btn"> Add </button>
    <input type="number" id="num1">
    <span> to </span>
    <input type="number" id="num2">
    <script src="app.js"></script>
</body>
</html>
  1. Inside the app.ts file add the following code. This TypeScript code emits the JavaScript file which we will use to take the values from the DOM, adds them, and logs the result on the browser console.
// DOM Elements

const addBtn = document.getElementById("add-btn");
const number1 = document.getElementById("num1")! as HTMLInputElement;
const number2 = document.getElementById("num2")! as HTMLInputElement;

// function to add two numbers and return the result
function addNum(num1:number, num2:number): number {
    return num1 + num2;
}

// event listener for add button
addBtn.addEventListener("click", function() {
    console.log(addNum(parseInt(number1.value), parseInt(number2.value)))
})
  1. To emit the app.js, go to your terminal and run the following command to compile the app.ts:

$ tsc —target es2015 app.ts

Make sure to run this inside the folder where your app.ts is located. As mentioned earlier, tsc is the TypeScript compiler. This will compile our app.ts and emit app.js and generate error messages in case of any errors.

The target flag is required to make sure the JavaScript emitted follows the ES2015 standard. By default, tsc emits ES3 standard which is pretty old.

  1. If you are using the code given above, it should work straight away. To see TypeScript in action, you need to remove the type annotations. Every time you make a change you need to compile the app.ts again. Changes that don’t conform to TypeScript will generate errors. It will still, however, generate the JavaScript and you can even run it but it might give unexpected results.

We've only scraped the surface of TypeScript's capabilities! The most important thing you can do to become more comfortable with typescript is to start using it in your personal projects. The more familiar you are with Typescript, the more easily you will be able to use it to produce clean code at your organization.

Hppy Coding!

 
Share this