Categories
Tutorials

Learning TypeScript

Typescript is a typed superset of JavaScript i.e., JavaScript along with some additional features including static typing, interfaces, classes, and more.

Moreover, it’s

  • An open-source programming language. 
  • Developed by Microsoft to help JavaScript Developers in many ways.
  • TypeScript code is compiled to plain JavaScript.

TypeScript vs. JavaScript

JavaScript

TypeScript

Dynamic scripting language

Static scripting language

Scripting language

Object-oriented programming

No static typing

Supports Optional static typing

Doesn’t supports interfaces.

Supports types and interfaces

Doesn’t supports optional parameters for functions

Supports optional parameters for functions

Doesn’t supports generics.

Supports generics.

Doesn’t supports modules.

Supports modules.

Why should you use TypeScript?

Some benefits of using TypeScript are as follows:

  • It helps to catch errors and bugs before runtime through a type system and thus results in the efficiency of JavaScript code.
  • It supports all the JS libraries and API documentation.
  • Typescript introduces static typing and supports Object-Oriented Programming to structure code and make code easier to refactor.
  • With TypeScript, you have a choice of which version of JavaScript you want to use as TypeScript supports ECMAScript.
  • TypeScript provides type definitions for external JavaScript libraries through a Definition file with the .d.ts extension.
  • You don’t have to make custom tools to access libraries in TypeScript as it uses NPM.
  • It makes code easier to understand and debug as it simplifies JavaScript code. Moreover, with the help of built-in documentation, it’s easier to read and access.
  • Typescript integrates well with React, Angular, and Vue. So, it increases productivity and ease.
  • TypeScript also provides strict null checks.

Before starting this tutorial, it is important to you should have a good understanding of OOP concepts and basic JavaScript, to make the most of this tutorial.

Environment Setup

For setting up TypeScript, you have 2 ways:

  • Either by installing TS Visual Studio Plugin OR
  • By using NPM (Node Package Manager)

Installing TypeScript using NPM,

  • First install NPM
  • After that, you have to install TS.
  • For this, type the following command in terminal ,
npm install -g typescript
  • If you want to check the version of TS, type the following command,
tsc -v
  • For compiling TS code, you have to run following command,
tsc YourFileName.ts
  • After this js file (of the same name you mentioned in command) will be created and you can use it on the browser.

Basic Syntax

Syntax defines a set of rules for writing programs. Every language specification defines its own syntax. A TypeScript program is composed of −

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

Your First TypeScript Code

Let us start with the traditional “Hello World” example −

var message:string = "Hello World"
console.log(message)

On compiling, it will generate following JavaScript code.

//Generated by typescript 
var message ="Hello World";
console.log(message);

Compile and Execute a TypeScript Program

STEP 1: Save the file with .ts extension.

STEP 2: To compile the file use the following command on the terminal window.

tsc Test.ts

STEP 3: The file is compiled to Test.js. To run the program written, type the following in the terminal.

node Test.js

Comments in TypeScript

Comments are a way to improve the readability of a program. TypeScript supports the following types of comments −

  • Single-line comments ( // ) − Any text between a // and the end of a line is treated as a comment
  • Multi-line comments (/* */) − These comments may span multiple lines.

Example

//this is single line comment 
/* This is a
 Multi-line comment
*/

TypeScript – Types

The Type represents the different types of values supported by the language. It checks the validity of the supplied values, before they are stored or manipulated by the program. This ensures that the code behaves as expected.

There are 3 categories of types in TypeScript:

  1. any
  2. Built-in types
  3. User-defined types

Any Type

Superset of all Typescript data types. If you want to opt-out for checking the type of variable, you can use any. So, it’s a dynamic type, which means the variable can be of any type.

Lets start with understanding the Any Type: You can assign any types to variable by following syntax:

let youVariableName: typeScriptType= assignedValue;

// examples:
let myVariable: any= 44;
myVariable = 'Assign string';
myVariable = true;

Built-in types

The following table illustrates all the built-in types in TypeScript:

Data type Keyword Description
Number number Double precision 64-bit floating point values. It can be used to represent both, integers and fractions.
String string Represents a sequence of Unicode characters
Boolean boolean Represents logical values, true and false
Void void Used on function return types to represent non-returning functions
Null null Represents an intentional absence of an object value.
Undefined undefined Denotes value given to all uninitialized variables

User-defined types

It includes Enumerations (enums), classes, interfaces, arrays, and tuple which will be discussed later.

TypeScript – Variables

A variable, by definition, is “a named space in the memory” that stores values. In other words, it acts as a container for values in a program. TypeScript variables must follow the JavaScript naming rules −

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

Declaring a Variable

A variable must be declared before it is used. Use the var keyword to declare variables.

To declare a variable in TypeScript it needs include a colon (:) after the variable name, followed by its type. Just as in JavaScript, we use the var keyword to declare a variable.

When declaring a variable you have four options available:

// Option 1: Variable stores the value of type string 
var name:string = ”John Doe”;

// Option 2: Variable is declared but value not set 
var name:string;

// Option 3: Variable type is based on the type of value assigned 
var name = "John Doe";

// Option 4: Using any type of variable 
var name;

Example:

var fname = "John";
var score1 = 50;
var score2 = 42.50;
var sum = score1 + score2;
console.log("First Name" + fname);
console.log("first score: " + score1);
console.log("second score: " + score2);
console.log("sum of the scores: " + sum);

On compiling, it will generate following JavaScript code.

var fname = "John";
var score1 = 50;
var score2 = 42.50;
var sum = score1 + score2;
console.log("First Name" + fname);
console.log("first score: " + score1);
console.log("second score: " + score2);
console.log("sum of the scores: " + sum);

The output of the above program is given below

First Name: John 
first score:50 
second score:42.50 
sum of the scores:92.50

Note: The TypeScript compiler will generate errors, if we attempt to assign a value to a variable that is not of the same type. Hence, TypeScript follows Strong Typing.

// will result in a compilation error as we have assigned string to a number
var num:number = "hello"

The Strong typing syntax ensures that the types specified on either side of the assignment operator (=) are the same. This is why the above code resulted in a compilation error.

TypeScript – Operator

Operators are used to combine two or more expressions, generally converting them to complex expressions.

The data on which operators work are called operands. Consider the following expression −

1 + 2 = 3

Here, the values 1, 2, and 3 are operands, while + and = are operators.

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

Lets look at some of the most commonly used ones:

Assignment operators

Assignment operators are used to assign values to javascript variables.

The following table contains commonly used Assignment operators:
Operator Usage Example
= Assigns value to variable let y:number  = 10;
+= Adds a value to a variable. let a:number  = 15;

a += 5;

-= Subtracts a value from a variable. let a:number  = 15;

a -= 5;

*= Multiplies a variable. let a:number  = 15;

a *= 5;

/= Divides a variable let a:number  = 15;

a /= 5;

%= Assigns a remainder to a variable let a:number  = 15;

a %= 6;

Arithmetic Operators

Arithmetic operators are used to perform arithmetic on numbers (javascript variables, expressions or literals).

The following table contains commonly used Arithmetic operators:

Operator Usage Example
“+”

(Addition)

Adds numbers let x:number  = 5;

let y:number  = 2;

let z:number  = x + y;

“-”

(Subtraction)

Subtracts Numbers let x:number  = 5;

let y:number  = 2;

let z:number  = x – y;

“*”

(Multiplication)

Multiplies Numbers let x:number  = 5;

let y:number  = 2;

let z:number  = x * y;

“/”

(Division)

Divides Numbers let x:number  = 6;

let y:number  = 2;

let z:number  = x / y;

“%”

(Modulus)

Returns Reminder of division  let x:number  = 5;

let y:number  = 2;

let z:number  = x % y;

“**”

(Exponentiation)

Raises the first operand to the power of 2nd operand let x:number  = 5;

let y:number  = 2;

let z:number  = x ** y;

“–”

(Decrement)

Decrements numbers let x:number  = 4;

x–;

let y:number  = x;

“++”

(Increment)

Increments numbers let x:number  = 4;

x–;

let y:number  = x;

Comparison operators

Comparison operators are used in logical statements for comparison (Equality or difference) between values or variables and upon evaluation return True or False.

The following table contains commonly used Comparison operators:

Operator Usage Example Returns
== Equal to let x:number  = 5;

x == 5

x == “5”

TrueTrue
=== Equal value or Equal type let x:number  = 5;

x === 5

x === “5”

TrueFalse
!= Not Equal to let x:number  = 5;

x != 7

True
!== Not Equal value or not Equal type let x:number  = 5;

x !== 5

x !== “5”

FalseTrue
> Greater than let x:number  = 5;

x > 7

False
< Less than let x:number  = 5;

x < 7

True
>= Greater than or equal to let x:number  = 5;

x >= 7

False
<= Less than or equal to let x:number  = 5;

x <= 7

True

Logical Operators

Logical operators are used in logical statements to determine logic between values or variables and upon evaluation return True or False.

The following table contains commonly used Comparison operators:

Operator Usage Example Returns
&& AND

(Returns True if both expressions are True else return False)

let x:number  = 7;

let y:number  = 2;

(x < 9 && y > 1)

(x < 9 && y < 1)

True

False

|| OR

(Returns False if both expressions are false else return True)

let x:number  = 7;

let y:number  = 2;

(x == 2 || y == 3)

(x == 7 || y == 0)

False

True

! NOT

(Returns True if expression is false else return true) 

let x:number  = 7;

let y:number  = 2;

!(x === y)

!(x > y)

True

False

TypeScript – Conditions

Conditional are used for decision making i.e., when you want to perform different actions based on different decisions.  

The following table shows conditional operators:

Operator Usage Examples
if Used to specify a block of code that should be executed if the condition is true else the if block will not be executed.

(Can be used alone) 

let x: number = 10, y = 20;

if (x < y)

{

// do something

}

else Used to specify a block of code that should be executed if the condition in “if block” is false.

(As you know else cannot be used alone it must be followed by an if statement )

let x: number = 10, y = 20;

if (x < y)

{

// do something

}

else

{

// do something else

}

else if Used to specify a block of code with a new condition that should be executed if the condition in “if block” is false.

(As you know else if cannot be used alone it must be followed by an if statement or an else if statement)

let x: number = 10, y = 20;

if (x < y)

{

// do something

}

elseif (x < 10)

{

// do something if condition in if is false and this condition is true

}

else

{

// do something if both of the above conditions i.e. in if and else if are false

}

switch Used to select one code block to be executed out of many.

(After the evaluation of expression in switch statement the resultant value is compared to every case and if there is a match that code block is executed. If none of the cases is matched then the default code block is executed.

Remember only one case is executed as after each case it breaks out of switch block )

let digit: number = 8;

switch(digit)

{

casex:

// code block

break;

casey:

// code block

break;

default:

// code block

}

TypeScript – Loops

Loops are used to execute a block of the code a number of times.

In JavaScript, we have 5 kinds of Loops described in table below:

Loop Keyword Usage & Syntax  Examples
for for (initialization; condition; increment/decrement)

{

// code block to be executed

}

(Note:

Statement 1 and 3 are optional so they can be omitted with a proper substitution instead of them)

for (let i = 0; i < 5; i++)

{

console.log (“Value of i is ” + i);

}

for in for (key in object) {

// code block to be executed

}

(Note:

It is used to loop through the properties of an object or array. Each iteration returns a key (x)and this key is used to access the value of the key)

let digits= {10,20,40};

for (let z in digits)

{

console.log(digits[z]);

}

for of for (variable of iterable) {

// code block to be executed

}

(Note:

It is used to loop through the iterable objects (Arrays, Strings, Maps, NodeLists etc).In every next iteration, next property value is assigned to the variable )

let language = “Python”;

for (let x of language)

{

console.log(char);

}

while while (condition) {

// code block to be executed

}

(Note:

The code block is executed as long as condition is true )

let i: number = 4;

while (i < 10)

{

console.log( “Value of i is ” + i )

i++;

}

do while do {

// code block to be executed

}

while (condition);

(Note:

Code block will be executed before checking if the condition is true, then the loop will be repeated as long as the condition is true.

Even if the condition is false , loop will be executed at least once. )

let i: number = 4;

do

{

console.log( “Value of i is ” + i )

i++;

}

while (i < 10);

TypeScript – Functions

Functions are a block of code designed to perform a particular task. Like functions in other programming languages, the syntax of TypeScript functions is almost similar.

Named Functions

In TypeScript, a named function is just like a normal function in any other language i.e., declaring a function by name and then calling it by that name.

Examples

(Without Parameters)

function display() {
   console.log("Hello Intern!");
}

display(); //Output: Hello Intern!

(With Parameters)

function addition(x: number, z: number) : number {
   return x + z;
}

addition(2,7); // returns 9

Anonymous Function

In TypeScript, an anonymous function is the function defined as an expression and this expression is stored in a variable. So, these functions are not called by name as they don’t have names, rather they are invoked by the variable name in which the function is stored.

Example

(Without Parameters)

let temp = function() { 
  console.log("Hello Intern!");
};
temp()//Output: Hello Intern!

(With Parameters)

let addition = function(x: number, z: number) : number { 
   return x + z;
}

Lamda Function

Lambda refers to anonymous functions in programming. Lambda functions are a concise mechanism to represent anonymous functions. These functions are also called as Arrow functions.

There are 3 parts to a Lambda function −

  • Parameters − A function may optionally have parameters
  • The fat arrow notation/lambda notation (=>) − It is also called as the goes to operator
  • Statements − represent the function’s instruction set

Lambda Expression

It is an anonymous function expression that points to a single line of code. Its syntax is as follows −

( [param1, parma2,…param n] )=>statement;

Example:

var foo =(x:number)=>10+ x
console.log(foo(100)) //outputs 110

Need more?