Learn TypeScript – A Brief Overview for Beginners


TypeScript is pure object oriented language with classes, interfaces and statically typed like Java. It helps programmers to write object-oriented programs and have them compiled to JavaScript, both on server side and client side. In other words, TypeScript is JavaScript plus some additional features.
The popular framework written in TypeScript is Angular 2.

Features of TypeScript:

  • It is just JavaScript.
  • It supports other JS libraries.
  • It is portable.
  • It is aligned with ES6 specifications.

Benefits of TypeScript include:

  • Compilation: TypeScript transpiler provides the error-checking feature. It will compile the code and generate compilation errors, if it finds some sort of syntax errors. This helps to highlight errors before the script is run.
  • Static Typing: TypeScript provides static typing and type inference system through the TLS (TypeScript Language Service). The type of a variable, declared with no type, may be inferred by the TLS based on its value.
  • Type definitions: TypeScript Definition file (with .d.ts extension) provides definition for external JavaScript libraries. Hence, TypeScript code can contain these libraries.
  • Object Oriented Programming: TypeScript supports concepts like classes, interfaces, inheritance, etc.

A TypeScript program is composed of –

  • Modules
  • Functions
  • Variables
  • Statements and Expressions
  • Comments


var message:string = "My first TypeScript file"


  • To compile the file use – tsc fileName.ts
  • To Execute the file use – node fileName.js
  • Multiple files can be compiled at once – tsc file1.ts, file2.ts, file3.ts

Object Oriented JavaScript:

TypeScript is object-oriented javascript. It considers a program as a collection of objects that communicate with each other via mechanism called methods.

class FirstTSClass{
display(message):void {
var obj = new FirstTSClass();
obj.message("My First TypeScript class.");

TypeScript Data Types:

TypeScript provides data types as a part of its optional Type System.

Data type classification:

  • Any: It is the super type of all types in TypeScript.
  • Built-in types: It includes number, string, Boolean, void, null, undefined.
  • User-defined Types: It includes Enumerations (enums), classes, interfaces, arrays, and tuple.

TypeScript Variables:

Use var keyword to declare variables. It must follow the JavaScript naming rules:

  • It can contain alphabets and numeric digits.
  • It cannot contain spaces and special characters, except the underscore (_) and the dollar ($) sign.
  • It cannot begin with a digit.

Variable declaration in TypeScript:

  • Declare its type and value in one statement.

//Syntax: var [identifier] : [type] = value ;

var message:string = "sample";

  • Declare its type but no value. The declared variable will be set to undefined.

//Syntax: var [identifier] : [type];

var message:string;

  • Declare its value but no type. The declared variable data type will be set to any.

//Syntax: var [identifier] = value;

var message = "Hello";

  • Declare neither value not type. The declared variable will be set to undefined and declared variable data type will be set to any.

//Syntax: var [identifier];

var message;

Strong Typing:

TypeScript follows Strong Typing. The Strong typing syntax ensures that the types specified on either side of the assignment operator (=) are the same.

This code will result in a compilation error:

var value:number = "One"; //compilation error

Type Assertion:

TypeScript allows changing a variable from one type to another. It refers to this process as Type Assertion.

//Syntax: var [identifier]:[type] = <target type> <source type> [value];

var value = '1';

var newValue:number = <number> <any> value;


Inferred Typing:

In TypeScript we can declare variable without a type. In this case, compiler will find the first usage of that variable and determine the type of the variable on the basis of the value assigned to it. This type should be same for that variable in the complete code block else compiler will throw an error.

var num = 2;

console.log("Value of num " + num);

num = "12"; // Compilation error - error TS2011: Cannot convert 'string' to 'number'.


TypeScript Variable Scope:

TypeScript variables can be of the following scopes:

  • Global Scope : accessed from anywhere within your code.
  • Class Scope : accessed using the object of the class.
  • Local Scope : accessible only within the construct where they are declared.

var global_var = 10;

class TypeScriptScope{

class_var = 5;

static static_var = 15;


var local_var = 4;

console.log("Local Variable :: "+ local_var);



console.log("Global Variable :: "+ global_var); 

console.log("Static variable :: "+ TypeScriptScope.static_var);

var typeScriptScope = new TypeScriptScope();

 console.log("Class variable :: "+ typeScriptScope.class_var);


TypeScript Operator, Statements and Loops:

The major operators in TypeScript can be classified as:

  • Arithmetic operators
  • Logical operators
  • Relational operators
  • Bitwise operators
  • Assignment operators
  • Ternary/conditional operator
  • String operator
  • Type Operator

The major statements in TypeScript can be classified as:

  • If statement
  • If…else statement
  • else..if and nested…if statement
  • switch statement
  • break
  • continue

The major loop in TypeScript can be classified as:

  • For loop
  • while loop
  • do…while loop

TypeScript Functions:

A. Parameterize Functions:

  • Positional Parameters:

//Syntax: function function_Name(arg1:[data type], arg2:[data type]){...}

function displayLog(line:number, message:string){

 console.log("Exception at "+line+" : "+message);


 displayLog(23,"Undefined variable!!");

  • Optional Parameters:

//Syntax: function function_Name(arg1:[data type], arg2:[data type], arg3?:[data type]){...}

function displayLog(line:number, message:string, module?:string){

 if(module != undefined){

 console.log("Exception in "+ module +" module at "+line+" : "+message);


 console.log("Exception at "+line+" : "+message);


  • Rest Parameters:

//Syntax: function function_Name(...args:[data type]){...}

function displayNumber(...table:number[]){

 for(i=0; i<table.length; i++){

 console.log("Argument - "+ (i+1) + " value :: "+ table[i]);



  • Default Parameters:

//Syntax: function function_name(arg1:[data type], arg2:[data type] = default_value) {...}

 function displayLog(line:number, message:string, module:string = "Test App"){

 console.log("Exception in "+ module +" module at "+line+" : "+message);


B. Anonymous Functions:

//Syntax: var func = function([args]){...}

var fullName = function(firstName:string, lastName:string){

 return (firstName +" "+lastName);


C. Function Constructor:

//Syntax: var func = new Function([args],{function logic with return result})

var addition = new Function("a","b","return a+b");

console.log("Function constructor example :: "+ addition(1,2));

D. Lambda Functions:

//Syntax: var lamdaFn = ([arg1,arg2,...arg n]) => statement;

var sumFn = (arg1:number,arg2:number) => (arg1 + arg2);

 console.log("Lambda Function Example :: "+sumFn(2,6));

E. Overload Functions:

To overload a function in TypeScript, you need to follow the mentioned steps:

    • Declare multiple functions with the same name but different function signature.
      • The data type of the parameter.
        //Syntax: function display(num:number)
        function display(str:string)
      • The number of parameters.
        //Syntax: function display(num:number)
        function display(num:number, str:string)
      • The sequence of parameters.
        //Syntax: function display(num:number)
        function display(str:string, num:number)
    • Declaration must be followed by the function definition.
      Note: If the parameter types differ during overload then parameter types should be set to any. For Case B, mark one or more parameters as optional during the function definition.
    • Finally, invoke the function to make it functional.


			function overloadFn(arg1:number):void;
			function overloadFn(arg1:number,arg2:string):void;

			function overloadFn(arg1:any,arg2?:any):void{
					console.log("Overload function having two arguments :: "+ arg1 +" and "+arg2);
					console.log("Overload function having single arguments :: "+ arg1 + " only.");


TypeScript Numbers:

TypeScript supports numeric values as Number objects which converts numeric literal to an instance of the number class using its constructor.

Properties of Numbers:

  • MAX_VALUE – 1.7976931348623157E+308.
  • MIN_VALUE – 5E-324.
  • NaN – Not a Number
  • prototype – Static property of Number object to assign new properties and methods to it.
  • constructor – To create Number object instance.

Methods of Number:

  • toExponential() – to display an exponential notation.
  • toFixed() – to display specific number of digits to the right of the decimal.
  • toLocaleString() – to return a string value version of the current number. It may vary according to a browser’s local settings.
  • toPrecision() – to display specified digits of a number(including digits to the left and right of the decimal). A negative precision will throw an error.
  • toString() – to return the string representation of the number’s value.
  • valueOf() – to return the number’s primitive value.

Example of Number Properties and Methods:

		interface Number{
			toSquare(): number;

		function showNumberProperties(){

			//Max Value
			var max_value = Number.MAX_VALUE;
			console.log("Maximum Value of Number :: "+ max_value);

			//Min value
			var min_value = Number.MIN_VALUE;
			console.log("Minimum Value of Number :: "+ min_value);

			var nonNumber = new Number("acs");
			console.log("Example of not a number :: "+nonNumber);

			Number.prototype.toSquare = function () : number{
				return this*this;
			var num:number = 10;
			console.log("Prototype example :: "+ num.toSquare());


		function showNumberMethods(){
			var numExp = 1234.567
			console.log("toExponential Example :: "+ numExp.toExponential());

			console.log("toFixed() Example :: "+ numExp.toFixed());
			console.log("toFixed(1) Example :: "+ numExp.toFixed(1));

			console.log("toLocaleString Example :: "+ numExp.toLocaleString("cs"));
			console.log("toLocaleString Example :: "+ numExp.toLocaleString("en"));

			console.log("toPrecision() Example :: "+ numExp.toPrecision());
			console.log("toPrecision(4) Example :: "+ numExp.toPrecision(4));
			console.log("toPrecision(5) Example :: "+ numExp.toPrecision(5));

			console.log("toString() Example :: "+ numExp.toString());
			console.log("toString(2) Example :: "+ numExp.toString(2));

			console.log("valueOf() Example :: "+ numExp.valueOf());


TypeScript Strings:

Example of String Properties and Methods:

		interface String{
			doPrefix(arg1:string) : string;

		function showStringProperties(){

			var str = new String("Hello World");
			console.log("Example of String constructor :: "+ str);

			console.log("Example of String Length :: "+ str.length);

			String.prototype.doPrefix = function(arg1:string):string{
					return (arg1+this);

			console.log("Example of String prototype :: "+str.doPrefix("String prototype "));


		function showStringMethods(){

			var strExp = "String Methods Example";

			console.log("charAt() example :: "+ strExp.charAt(7));

			console.log("charCodeAt() example :: "+strExp.charCodeAt(7));

			console.log("concat() example :: "+strExp.concat("concat method"));

			console.log("indexOf() example :: "+strExp.indexOf("Example"));

			console.log("lastIndexOf() example :: "+strExp.lastIndexOf("h"));

			console.log("localeCompare() example :: "+strExp.localeCompare("String Methods Example"));

			console.log("replace() example :: "+strExp.replace("Methods","Functions"));

			console.log("search() example :: "+strExp.search("Methods"));

			console.log("slice() example :: "+strExp.slice(0,7));

			console.log("split() example :: "+strExp.split(" ").length);

			console.log("substr() example :: "+strExp.substr(7,strExp.length));

			console.log("substring() example :: "+strExp.substring(7,strExp.length));

			console.log("toLocaleUpperCase() example :: "+strExp.toLocaleUpperCase());

			console.log("toLocaleLowerCase() example :: "+strExp.toLocaleLowerCase());

			console.log("toLowerCase() example :: "+strExp.toLowerCase());

			console.log("toUpperCase() example :: "+strExp.toUpperCase());

			console.log("toString() example :: "+strExp.toString());

			console.log("valueOf() example :: "+strExp.valueOf());



TypeScript Arrays:

Example of Arrays Properties and Methods:

		//Simple Array
		var employeeNameArray : String[]; //declaration
		employeeNameArray = ["Test Name 1","Test Name 2"]; //initialization
		console.log("Array Example :: "+ employeeNameArray[0] +" And "+employeeNameArray[1]);

		//Declaration and initialization in single statement
		var numArr:number[] = [1,2,3,4,5,6];
		console.log("Array declaration and initialization in single statement :: "+ numArr);

		//Array Object
		var arrObj:number[] = new Array(10);
		console.log("Array object example ::");
		for(var i=0; i<10; i++){
			arrObj[i] = (i+1)*2;
			console.log((i+1) + "*2 = "+arrObj[i]);

		//Array Constructor
		var arrConstructor:string[] = new Array("one","two");
		console.log("Array constructor example :: "+arrConstructor);

		//Arrays methods

		function everyFn(element, index, array){
			return (element< 11);

		function filterEvenNum(element, index, array){
			return (element % 2 === 0);

		function cube(element, index, array){
			return Math.pow(element,3);

		function smallerValue(arg1,arg2){
			return (arg1<arg2?arg1:arg2); 		} 		function someFn(element){ 			return (element >= 10);

		function sortFn(arg1,arg2){
			return (arg1 > arg2 ? -1 : arg1==arg2 ? 0 : 1)

		function displayOdd(arg:number[]){
			console.log("Arrays as parameter example :: "+arg)

		function showArraysMethods(){

			var oddArr:number[] = [1,3,5,7,9];
			var evenArr:number[] = [2,4,6,8,10]; 

			var concatArr:number[] = oddArr.concat(evenArr)
			console.log("concat() example :: "+ concatArr);

			var everyExample = concatArr.every(everyFn);
			console.log("every() example :: "+ everyExample);

			var filterExample = concatArr.filter(filterEvenNum);
			console.log("filter() example :: "+ filterExample);

			console.log("forEach() example :: ");
			concatArr.forEach((element,index) => {
				console.log("Value at position-"+index+" :: "+element);

			console.log("indexOf() example :: "+ concatArr.indexOf(5));

			console.log("join() example :: "+ concatArr.join("-"));

			console.log("lastIndexOf() example :: "+ concatArr.lastIndexOf(10));

			console.log("map() example :: "+ evenArr.map(cube));

			console.log("pop() example :: "+ oddArr.pop());

			console.log("push() example - length of oddArr before push :: "+ oddArr.length);
			console.log("push() example - length of oddArr after push :: "+ oddArr.push(11));

			console.log("reduce() example :: "+ concatArr.reduce(smallerValue))

			console.log("reduceRight() example :: "+ concatArr.reduceRight(smallerValue))

			console.log("reverse() example :: "+ concatArr.reverse())

			console.log("shift() example :: "+ oddArr.shift())

			console.log("slice() example :: "+ concatArr.slice(1,7));

			console.log("some() example :: "+ concatArr.some(someFn));

			console.log("sort() example :: "+ concatArr.sort(sortFn));

			var spliceFnExm = concatArr.splice(2,0,16);
			console.log("splice() example of adding new element :: "+ concatArr);
			spliceFnExm = concatArr.splice(2,1);
			console.log("splice() example of removing the element :: "+ concatArr);

			console.log("toString() example :: "+ concatArr.toString());

			var unshiftArrExm = concatArr.unshift(11,12);
			console.log("unshift() example :: "+ concatArr);

			//Array destructuring
			var[first,,second] = concatArr;
			console.log("Array destructuring example :: "+ second)

			//for...in loop
			for (var index in concatArr) {

			//multidimensional array
			var multidimArr:String[][] = new Array();
			for (var outer = 0; outer < 3; outer++){
				multidimArr[outer] = new Array(3);
				for(var inner = 0; inner < 3; inner++){
					multidimArr[outer][inner] = new String("*");

			console.log("Multidimensional Array declaration and initialization Example :: "+ multidimArr)

			//Arrays as argument




Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s