What is typescript and why use it?

The most human definition would be.

  1. It is super set of Javascript. Since Javascript is an interpreted language, it needs to run to test if our code is valid.
  2. Typescript compiler compiles Typescript code to generate Javascript code and reports any error at compile time.
  3. Supports object oriented programming (classes, inheritance..)
  4. Can improve your code quality, error handling when compared to Javascript.

What are we going to cover

  1. Installation
  2. Basic Types (Array, Void, Tuple)
  3. Functions
  4. Interface
  5. Class
  6. Inheritance
  7. Private, Protected and Public Variables
  8. To illustrate that Typescript is able to detect javascript errors, we would be making one or two intentional errors

Getting Started With TypeScript

Installation

Install TypeScript globally using npm

npm install -g typescript

Hello World

Create a new .tsfile (say index.ts)

Inside index.tsfile, write a simple console.log statement

let myString: String = "hello World";
console.log(myString);

From terminal do

tsc index.ts

This will generate index.jsfile with the content in below snippet. The reason they both looks the same is that in our TypeScript file, we haven’t used typescript yet.

var myString = "hello World";
console.log(myString);

Getting our First Error with TypeScript

let myString: String = 2;
console.log(myString);

Now when we run command tsc index.tsfrom terminal, this what we would see in console

index.ts:1:5 - error TS2322: Type '2' is not assignable to type 'String'.
1 let myString: String = 2;
      ~~~~~~~~

but this will still create Javascript file

Converting our typescript into Javascript in real time

In our terminal, navigate to the folder having index.ts file and run following command in terminal

tsc index.ts -w

Now whenever we save our typescript file, the -wflag (watch)  will come into play and will convert our typescript into javascript automatically and hence we don’t need to do run tsc index.ts​every time we make changes in our typescript file

Array

Array of types

let strArr: string[];
strArr = ["Rohit", "Bhatia"];
console.log(strArr);

Here, we have declared Array type of string. So, if we do something like this

let strArr: string[];
strArr = [5, 9];
console.log(strArr);

This will throw an error since we are saying that our Array will only contain string but we are actually pushing/having numbers in it.

We can also declare array type like this

let strArr: Array;

this is equivalent to

let strArr: string[];

Tuple

Tuple is an array whose type is known i.e consider this array.

let stringandTuple = [string, number]

Here we are saying that our array stringandTuple ‘s first element will be string and the second element would be number. Hence, in our code snippet below, our first element is a string and second element is a number.

stringandTuple = ["Rohit", 4]

Note: Here our third number can be anything i.e [“Rohit”, 4, “shivom”] or [“Rohit”, 4, 5]</code>

Functions in TypeScript

With function we can add type to parameters and function’s return type

function getSum(num1: number, num2: number): number {
  return num1 + num2;
}
console.log(getSum(3, 4));

Explaining the above code, when we define something like this,

function getSum(num1: number, num2: number)

we are saying that parameters being passed i.e num1 and num2 should be numbers. So, if we write this code  console.log(getSum("Rohit", "Bhatia")) , it would throw an error, because our function is expecting a number and we are passing a string.

The :number declared after the parameters i.e ): number { tells that we want our function to return a number. So, in the above function the statement return num1 + num2; won’t throw an error but if we would have returned something else, say return "Rohit" , it would have thrown an error, because we are specifying that our function would return a number but rather it is returning a string here.

Void functions in TypeScript

Void means that function won’t return anything For example if we do something like this

function getSum(num1: number, num2?: number): void {
  return num1 + num2;
}
console.log(getSum(3, 4));

This would throw an error since we are returning a number num1 + num2 .

But, if we do something like this,

function getSum(num1: number, num2?: number): void {
  return
}
console.log(getSum(3, 4));

then,  it won’t throw any errors

Interface

Interface is sort of like a Schema for our object/ or creating our own type or something which an object should adhere to.

Consider this function

function showToDo(todo: {title: string, text: string}) {
return todo.title + ":" + title.test 
}

To clean this up we can create interface

interface Person {
  name: string;
  age: number;
}
function personDetails(person: Person) {
  return person.name + person.age;
}
let newPerson = {
  name: "Rohit",
  age: 18
};
personDetails(newPerson);

In the above code, we have replaced this untidy looking snippet

(todo: {title: string, text: string})

into

function personDetails(person: Person) {

Note: when we say person: Person we are saying that our function will take an argument known as person and that person should have the schema defined in our interference.

Also, another advantage of using interface is that we can even re-use them for a function taking something as an argument with similar schema

Classes in TypeScript

Typescript’s default target is ES5 so it transpiles to JS code that can execute on browsers as old as IE11. If you set ES6 as target, you’ll notice that JS classes will be used

class User {
  name: string;
  email: string;
  constructor(name: string, email: string) {
    this.name = name;
    this.email = email;
  }
}
let newUser = new User("Rohit Bhatia", "iro@gmail.com");
console.log(newUser); //This is just a constructor

This would be equivalent to this in ES5

var User = /** @class */ (function () {
    function User(name, email) {
        this.name = name;
        this.email = email;
    }
    return User;
}());
var newUser = new User("Rohit Bhatia", "iro@gmail.com");
console.log(newUser);

Here @class is just a comment

In TS classes we can also set properties to private, protected, and public.

We will explore the difference as we move on

Public and Private

class User {
  private name: string;
  email: string;
  constructor(name: string, email: string) {
    this.name = name;
    this.email = email;
  }
}
let newUser = new User("Rohit Bhatia", "iro@gmail.com");
console.log(newUser.email && newUser.name);

Here notice

private name: string;
email: string;

When we are doing ​private name string , we are saying that this property cannot be accessed from outside the class and hence by the definition. when we do

console.log(newUser.email && newUser.name);

TypeScript will throw an error saying name is private and hence shouldn’t be accessed from outside

Inheritance and Protected Variables

Protected Variable: Protected Variables are variables which can only be accessed by class and the class inheriting it and cannot be accessed from outside the class

Note: Private can’t be accessed even by the class inheriting it

Using above example as our base class

class User {
  private name: string;
  email: string;
  constructor(name: string, email: string) {
    this.name = name;
    this.email = email;
  }
  
   checkUserData(id: number) {
    console.log(
      "This user name is" +
      this.name +
      "his email address is" +
      this.email +
      "and his ID is" +
      id
    );
  };
  
}

We want to inherit properties of the above class.  To do that, we use the word extendsand so to inherit we will write something like

class College extends User {
  id: number;
  // annotate types on function parameters
  constructor(name: string, email: string, id: number) {
    super(name, email);
    this.id = id;
  }
  // a method on the prototype, not function property
  checkUserData() {
    super.checkUserData(this.id);
  };
}

and then, we call it by doing something like this

let newUser = new College("Rohit Bhatia", "iro@gmail.com", 4556);
console.log(newUser.checkUserData());

Understanding what is happening above

  1. We are extending College to inherit properties from User
  2. We are creating new property for user known as id
  3. To use the inherit properties we use super() and specify what all properties we are going to use.
checkUserData() {
    super.checkUserData(this.id);
  };

4. In the above code snippet, we are inheriting method from class User      and calling it in child class College, to call the method we use super.methodName

Note: By default, typescript will compile to ES5 but if we change the default to Es6, you can see the equivalent code in JS having class

The End

With that we have went through all the major concepts of TypeScript. Again this isn’t complete guide but a quick run for you to understand the major concepts of typescript