TypeScript Tutorial for Beginners

By Dhiraj Ray, 20 January,2018   1K
typescript

Today we will learn about typescript and this tutorial provides fundamentals of typescript and try to cover most of the topics such as typescript variables, functions, enum, class, access modifiers, interface, typecasting, arrow functions and many more for beginers to get started with angular.Typescript is a superset of javascript and it adds optional static typing to javascript. You can do everything in typescript which you were doing in javascript.Typescript is free and open-source programming language developed and maintained by Microsoft.Typescript compiles based on ES5 which is supported by all browsers.

Installing TypeScript

You can easily install typescript with the help of NPM. For this first install Node Js on your machine. To download and install it you can visit to NodeJs official website and follow the instructions.After this you can use npm -version to check if it is installed.Now to install typescript compiler use following command.

npm install -g typescript
tsc -version

Running Typescript

1. Traverse to your typescript workspace and create a file as hello.ts with below code

function greeter(person) {
    return "Hello, " + person;
}

let user = 'Devglan';

console.log(greeter(user));

2. compile it using tsc hello.ts. This will generate a hello.js file in the same location.

3. Run as node hello.js. This will print Hello, Devglan in the console.

Variable in TypeScript

A variable in typescript can be boolean, string, any or number[] and any variable in typescript can be declared using keyword - var and let. But it is always recommended to use let keyword to define a variable in typescript as it provides type safety.Following are the different ways to define a variable in typescript.

let num : number; //Defines a number variable
let str : String = 'Devglan'; //Defines a string variable and initialises to Devglan 
let array : String[] = ['a', 'b', 'c']; //Defines a string array variable
let random : any[] = ['a', 1, true];

The advantage of this different variable type is - a variable declared as number can not hold a string value as typescript compiler will show you a compile error. Similarly, if you have a variable declared as any can hold any data type. This is similar to var keyword in javascript.

Typescript also provides support for enum similar to object oriented language to declare constant.Following is an exampple to declare enums in typescript.

enum Role {Admin, User,SuperAdmin};
let role = Role.Admin;

Arrow Functions

Arrow functions are similar to lambda expression in java.We can execute inline functions using it. Suppose we have a code of block as follow:

var greet = function greeter(person) {
    console.log( "Hello, " + person);
}

This can be replaced using arrow function as var greet = (person) => console.log(person);

Interface in TypeScript

Interface is used to define reusable custom data types. For example, if you want to create a reusable User object then you can have name, age, gender as its types.

interface User {
    name : String
    age : number
    gender : String
}

And this can be used as a reusable type as below:

let createUser = (user : User) =>{

}

TypeScript Class

Class is a logical entity that has variables and functions that are highly related to perform single operation. The difference between a class and an interface is that class can have implementation inside it whereas an interface does not have any implementation inside it. Following is a simple User class that has fields and methods:

class User {
    name : string
    age : number
    gender : string

    createUser(userr : User){
        //create user
    }
}

Now we can instantiate this class and use it's method in following ways

let user = new User();
user.name = 'Dhiraj';
user.gender = 'Male';
user.age = 23;
user.createUser(user);

TypeScript Constructor

Constructor is used to instantiate a class.The declaration of a constructor is similar to a method without any return type.Following is the declaration of constructor for class defined above.

constructor(name : string, age : number, gender : string) {
        this.name = name;
        this.age = age;
        this.gender = gender;
    }

Now doing so the line let user = new User(); will show compiler error as there is no matching constructor in the class definition and typescript does not support constructor overloading.To remove this compile error, you can make the constructor parameters optional as follow:

 constructor(name? : string, age? : number, gender? : string) {
        this.name = name;
        this.age = age;
        this.gender = gender;
    }

Access Modifier in Typescript

Access modifier is used to modify the access level of the variables and methods used inside any class.We have 3 different access modifiers in typescript - public, private and protected. By default all the members are public and tht's the reason we were able to initialise class variable from outside the class.Following is the syntax to use access modifiers.

    private name : string
    private age : number
    private gender : string

Conclusion

In this article we learned about getting started with typescript with variable, class, interface, access-modifier. If you have anything that you want to add or share then please share it below in the comment section.

Further Reading on typescript

1. Rxjs Tutorial

2. Angular Material App

3. Install Nginx Php Mac

4. Nodejs Basic Tutorial

5. Nodejs Chat Socket Io Example

If You Appreciate What We Do Here On Devglan, You Should Consider: