Introduction to Typescript for Javascript Programmers

Introduction to Typescript for Javascript Programmers

TypeScript stands in an unusual relationship to JavaScript. TypeScript offers all of JavaScript’s features and an additional layer on top of these: TypeScript’s type system. This means that your existing working JavaScript code is also TypeScript code. The main benefit of TypeScript is that it can highlight unexpected behavior in your code, lowering the chance of bugs.
This article will introduce to the additional features Typescript provides on top of Javascript. Let's dive in!

Why Typescript?

Consider the Javascript code:

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

const result = add(2, 5);

console.log(result);

If you have some experience with JS, you probably know the output of this program, i.e 7 as a number. Now, consider this code with a few changes:

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

const result = add('2', '5');

console.log(result);

What do you think the output will be now?
Yes, it's 25 but as a string.
The problem is that both the above codes will work fine on Javascript without giving any error, but if we want to write a function that takes only numbers as arguments and returns their sum, we can't actually do that easily in Javascript. This is what Typescript solves with its type system.

Types in Typescript

With typescript, you can basically define a type for a variable, which will imply that this variable can store only this type of data and not any other type. For example:

let age: number;
age = 20;
// age = 'jo'; error

In the above code, we declared that the age variable will store only number type, so this will throw me an error if I try to store let's say a string or a boolean type in it.

You can also define a variable as an array or an object type.

let hobbies : string[];
hobbies = ['Cooking', 'Dancing'];
// hobbies = ["Cook", "Sports", 1]; error

let person : {
    name: string;
    age: number;
}
person = {
    name: 'Lakshya',
    age: 20,
    // isEmployee: true, error
}

Interface

For defining an object's shape we can define interfaces, so that we can also reuse it.

interface Person : {
    name: string;
    age: number;
}
const person : Person = {
    name: 'Lakshya',
    age: 20,
}
const people : Person[] = [
    {
        name: 'Lakshya',
        age: 20
    },
    {
        name: 'Kunal',
        age: 20,
    }
];

Union

To define a variable that can contain multiple types, we use unions.

let message : string | number = 'hi'; // to allow both string and numbers
message = 20; // no error

Generics

Generics provide variables to types. A common example is an array. An array without generics could contain anything. An array with generics can describe the values that the array contains.

type StringArray = Array<string>;
type NumberArray = Array<number>;
type ObjectWithNameArray = Array<{ name: string }>;

You can declare your own types that use generics:

interface Backpack<Type> {
  add: (obj: Type) => void;
  get: () => Type;
}

// This line is a shortcut to tell TypeScript there is a
// constant called `backpack`, and to not worry about where it came from.
declare const backpack: Backpack<string>;

// object is a string, because we declared it above as the variable part of Backpack.
const object = backpack.get();

// Since the backpack variable is a string, you can't pass a number to the add function.
// backpack.add(23); error

You can also use Generics with functions:

function insertAtBeginning<T> (array: T[], value: T) { // to specify that array and value parameter should be of same type
    const newArray = [value, ...array];
    return newArray;
}

const demoArray = [1, 2, 3];
const updatedArray = insertAtBeginning(demoArray, -1);

// const updatedArray = insertAtBeginning(demoArray, 'hello'); error

Next Steps

So, this was the basic introduction of Typescript and mainly its type system.
You are ready to start writing Typescript, if you already know Javascript, after reading this. Trust me, you will learn more while writing it.
And, of course, you can check out the official documentation of Typescript to get a deep dive into Typescript.

Shout out to the amazing course, React - The Complete Guide, on Udemy by Academind taught by Mr. Maximilian Schwarzmüller which helped me write this.

That's it! Happy Learning!