Home » JavaScript » TypeScript Tutorial for Beginners

About Dhiraj Ray

Dhiraj Ray
He is a technology savvy professional with an exceptional capacity to analyze, solve problems and multi-task. He is an avid reader and a technology enthusiast who likes to be up to date with all the latest advancements happening in the techno world. He also runs his own blog @ devglan.com

TypeScript Tutorial for Beginners

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.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.

Published on Web Code Geeks with permission by Dhiraj Ray, partner at our WCG program. See the original article here: TypeScript Tutorial for Beginners

Opinions expressed by Web Code Geeks contributors are their own.

(0 rating, 0 votes)
You need to be a registered member to rate this.
Start the discussion Views Tweet it!
Do you want to know how to develop your skillset to become a Web Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. Building web apps with Node.js
2. HTML5 Programming Cookbook
3. CSS Programming Cookbook
4. AngularJS Programming Cookbook
5. jQuery Programming Cookbook
6. Bootstrap Programming Cookbook
and many more ....
I agree to the Terms and Privacy Policy
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments