The TypeScript Language

The TypeScript Language

·

6 min read

Hello! Today we will look at the TypeScript language. I'm learning it and I will use it in future posts so it's good to make a post about it.
You can follow the examples I will make on this online TypeScript compiler.


Theory

TypeScript is a strongly typed language created by Microsoft in 2012. We can describe TypeScript as a super-set of JavaScript with types.

But let's try learning the purpose of types from this example: we have a function add that adds two numbers and then we call it.
Here's how that would be in Js:

const add = (a, b) => {
    return a + b;
}

And here's how we would write it in TypeScript:

const add = (a: number, b: number) => {
    return a + b;
}

Now let's run two tests:

  1. We add two numbers: 5 and 2 => add(5, 2);

  2. We add two strings: "Hash" and "node" => add("Hash", "node");

Here's the output and the errors for JavaScript:

>> "7"
>> "Hashnode"
NO ERRORS

And here's for TypeScript:

>> "7"
>> "Hashnode"
"Error: Argument of type 'string' is not assignable to parameter of type 'number'."

So, we see that in JavaScript we get no errors for the second test. If we wanted to have an error we should have first checked if the type of the two inputs were numbers and then return the sum (more lines of code). Meanwhile, in TypeScript we get the error when writing the code (if using tools like VSCode) and the error in the console.
Now let's look at all the types and other features.

The Types

In TypeScript, types are divided into primitives and others. Here's the list of some everyday types:

  • string (primitive);

  • number (primitive);

  • boolean (primitive);

  • undefined;

  • any;

  • never;

Implicit and Explicit types

TypeScript works like JavaScript so if a certain type isn't set, TypeScript will assign the type of the value assigned, this is called implicit type. For example:

let age = 22;
console.log(typeof age)
>> "number"

On the other hand, assigning a certain type means it is an explicit type. For example:

let fullName: string = "Robert Williams";
console.log(typeof fullName);
>> "string"

Arrays and Any type

Arrays can be written in two different methods (the output doesn't change):

let clientsIds: number[] = [132, 653, 124, 749];
const addClientId = (list: number[], id: number) => {
    list.push(id);
}

console.log(clientsIds);
addClientId(clientsIds, 255);
console.log("Added client 255. New list: " + clientsIds);
>> "[132, 653, 124, 749]"
>> "Added client 255. New list: 132, 653, 124, 749, 255"

Is the same thing as:

let clientsIds: Array<number> = [132, 653, 124, 749];
const addClientId = (list: Array<number>, id: number) => {
    list.push(id);
}

console.log(clientsIds);
addClientId(clientsIds, 255);
console.log("Added client 255. New list: " + clientsIds);
>> "[132, 653, 124, 749]"
>> "Added client 255. New list: 132, 653, 124, 749, 255"

With the any type we declare something that can be of any type that you want, so you can use it for something you don't know what will be. For instance:

const returnType = (data: any) => {
    return typeof data;
}

console.log(returnType(22));
console.log(returnType(false));
console.log(returnType("hello"));
console.log(returnType([2, 4, 2, 1]));

>> "number"
>> "boolean"
>> "string"
>> "object"

Union Types

Sometimes we use variables that can be more than one type, with union types we can declare a variable as more than one type. Here's an example:

// union types are made by separating types with "|"
const printUserId = (id: string | number) => {
    console.log(id, typeof id)
}

printUserId(2542);
printUserId("alpha");
>> "2542,  number"
>> "alpha,  string"

In this example, we created a function to print the ID of a User and the type of that ID. This ID can either be a string or a number.

Create a Type

We can also create our type for our project. For example, let's create a boolean for a state made with integers "on" or "off":

type Status = "on" | "off";

let state: Status; // we declare a variable of our type
state = "on"; // we assign it a value between "on" and "off"

console.log(state);
>> "on"

Classes and Interfaces

Classes

JavaScript already offers the possibility to create classes. TypeScript boosts this possibility by implementing type-checking and static properties. Let's look at a class that creates a new type of Pizza.

class CreateAPizza {
  static create(pizza: { name: string; toppings: string[] }) {
    return { name: pizza.name, toppings: pizza.toppings };
  }
}

const newPizza = CreateAPizza.create({
  name: 'Italian',
  toppings: ['tomato sauce', 'mozzarella cheese'],
});

console.log(newPizza);
>> "
{
  "name": "Italian",
  "toppings": [
    "tomato sauce",
    "mozzarella cheese"
  ]
} 
"

Including the static property in the create method lets us use it without creating an instance of it.

Interfaces

On the other hand, Interfaces are a structural component that offers the possibility to determine an object and its properties' types:

interface Pizza {
  name: string;
  toppings: string[];
}

class PizzaMaker {
  static create(event: Pizza) {
    return { name: event.name, toppings: event.toppings };
  }
}

const newPizza = PizzaMaker.create({name: "Italian", toppings: ["tomato sauce", "mozzarella cheese"]});
console.log(newPizza);
>> "
{
  "name": "Italian",
  "toppings": [
    "tomato sauce",
    "mozzarella cheese"
  ]
} 
"

The unfortunate thing with interfaces is that they don't offer a direct way to create methods.

Installation and Usage

In the second part of this post, we're gonna look at how to install and use TypeScript.

Installation using Node

First of all, make sure you have Node installed, if you haven't go over to this website and install it.

After that we'll use npm to install TypeScript with this command:

$ npm i -g typescript

And check if it has been installed with this command:

$ tsc -v
>> "Version ..."

We've finally installed TypeScript.

Our First Program

Now we will create our first TypeScript program. First, go to your preferred IDE or code editor (I am using VsCode) and create a new .ts file (if you wanna use conventions call it index.ts).

Now open it and write a simple line of code that we can test:

// /index.ts
console.log("TypeScript is Working!");

Run using Node

To run it using Node we have to convert it to JavaScript code first. To do this we can use the tsc command followed by the file. This will convert the .ts file to a .js one. Then we can use Node to run it:

$ tsc index.ts
$ node index.js
>> "TypeScript is Working!"

Run using Ts-Node

A package called ts-node offers the possibility to run .ts files directly without converting them to .js ones. To use it we need to install the package via npm:

$ npm i ts-node

Then we run our .ts files using ts-node:

$ ts-node index.ts
>> "TypeScript is Working!"