10X Sale
kh logo
All Courses
  1. Tutorials
  2. Mobile App Development

Introduction to TypeScript

Updated on Sep 23, 2025
 
10,989 Views

Before beginning with Ionic, it is essential to have good knowledge of Angular. Angular programs are written in TypeScript.

But before looking at TypeScript we will also take a brief look at Node JS. Node JS is a server environment that runs JavaScript. The easiest way to run TypeScript is within Node.

Node comes with its package manager - NPM - Node Package Manager. NPM is the world’s largest package repository. It is the most common mechanism to distribute open source software. TypeScript, Angular and Node are made available via node.

At the most fundamental level it is important to get a sense of what TypeScript is and what the programming language looks like. This is done best by means of practical examples. It is recommended that you try the examples in this tutorial before proceeding to Ionic.

From the TypeScript website...

Image

  1. TypeScript is a 'typed' superset of JavaScript. It compiles into plain JavaScript.
  2. Ionic uses TypeScript because it uses Angular. And Angular uses TypeScript. Hence, the need to learn TypeScript.
  3. Traditionally, enterprise languages have been written in object oriented programming languages that are scalable. The primary advantage of using an OOP language is that it can handle complexity well. As applications grow in size and age, they grow complex. The programming language should allow building large programs, while still staying modular. TypeScript, in contrast to JavaScript is Object Oriented.
  4. JavaScript is a loosely typed language. This means that you do not need to specify what kind of data will be stored in a variable in advance.
  5. TypeScript is strongly typed and forces you to specify the type for variables that you use. This static typing is optional.
  6. Code editors like Visual Studio Code offer enhanced support for TypeScript.
  7. Further, JS files can be saved as TypeScript files.

Installation

As mentioned above, TypeScript is made available through Node JS. If you do not have Node already installed, you can install it from:

https://nodejs.org/en/download/

Once you have node installed, you have Node’s package manager available. TypeScript can be installed using:

  1. npm install -g TypeScript
  2. “-g” means that TypeScript is installed globally and can be accessed from any folder.

A Further Note on Node

TypeScript compiles to JavaScript and Node executes the JavaScript files. To be precise, Node is a JavaScript runtime environment, much like JRE for Java. It contains everything that JavaScript needs to run.

It is built on Chrome’s JavaScript V8 Engine. It converts JavaScript to Machine Code

What does the JavaScript V8 Engine do in Chrome/ Node

  1. Heap - Allocates memory
  2. Call Stack - Records where in the program we are? Which function is being called?
  3. It is single threaded, meaning, it does one thing at a time
  4. Handles Blocking Behaviors- In the past, the entire browser used to “freeze” when there was some processing going on. These items are queued in an “Event Loop” until the stack is empty.
  5. Web APIs - It offers libraries like AJAX. DOM,

Why Not Write in JS Directly

Each browser has its own JavaScript Engine. Chrome runs V8, Firefox runs SpiderMonkey, and Internet Explorer, Chakra. Each has its own compatibility issues.

https://kangax.github.io/compat-table/es6/

  1. TypeScript compiles to JavaScript standard ECMA Script. Browsers are compliant at different levels. Thus TypeScript can run on any browser.
  2. TypeScript offers a better set of tools like Intellisense, Debugging, etc.

Angular and TypeScript

Angular 2 is a complete rewrite of AngularJS, which was written in JavaScript. Microsoft added annotations to TypeScript language, and made it the language for the development of the Angular 2 framework itself.

Code Editor/ IDE

Download and install Visual Studio Code from https://code.visualstudio.com/

The TypeScript Language

With this background, we are good to get started with TypeScript. This will be a brief introduction so that we know enough to get introduced to Angular/ Ionic.

Hello World

1. Create a new folder TypeScript Tutorial

2. Open Visual Studio Code and import the folder

Image

3. And create a new file (Hello.ts) by right clicking on the folder in the folder and type
console.log(“Hello World”)

Image

4. Save the file

5. Open the integrated terminal

Image

Image

6. type tsc hello.ts

7. You will notice that TypeScript has been compiled into a JavaScript file hello.js

8. On the command prompt run node hello. The JavaScript engine within node will run the JavaScript file and print “Hello World” on the console

Image

In addition to doing a “hello world” in TypeScript, you now know how to import a folder and create files in TypeScript. You also now know how to run commands within the editor.

Variables

A variable is used to store, retrieve and manipulate information in a programming language. TypeScript uses the key words let and const to declare variables.

let greeting = “hello world”
console.log(greeting)

const greeting2  = “hello world”
console.log(greeting2)

A variable declared using Const needs to be initialized and it cannot be reassigned.

ImageImage

In the images above, it is seen that Visual Studio Code flags the variable “a” with an error when it is not initialized and when it is reassigned a value.

Variable Types

TypeScript supports 3 data types. As mentioned earlier using data types is optional.

1. Boolean

2. Number

3. String

let name : string = “Josh” 
let age : number = 22 
let isStudent : boolean = true

4. Variables can be assigned as null or undefined

let name : string = null
let name : string = undefined

5. Types are checked in compile time

Image

6. Allows intellisense in the editor. Intellisense is Microsoft’s way of intelligent code completion.

Image

Expressions

An expression is a combination of operators and operands. Operands can be constants, variables or other expressions.

Image

a= 12 * b + c;

12, b, c are operands in the expression and =,*,+ are operators.

TypeScript supports the following operators:

Arithmetic operators

+, -, *, /, %, ++, --

Logical operators

&& (AND), || (OR), ! (NOT)

Relational operators

>, <, >=, <=, != (not equal), == (equal)

Assignment operators

=, +=, -=, *=, /=, %=

Ternary/conditional operator

let t = 10>20?”smaller”:”larger”; Will store “smaller” in t

TypeOf Operator

“ var a = 12; console.log(typeof a)” will return “number”

Bitwise operators

& (AND). | (OR), ^ (XOR), ~ ( Not), << (Left Shift), >> (Right Shift), >>> (Right shift with Zero)

Template Strings

A template string is a string which is enclosed within back-tick characters (`). It can include expressions within ${ }. TypeScript replaces placeholders with real values. Template strings are a better option to use when compared to string concatenation.

let name = 'Josh';
console.log('name ' + name)
let statement = `I am
${name}`
console.log(statement)

The output will be:

Image

Arrays

An array is a data structure that contains a group of elements. Typically these elements are all of the same data type, such as a number or string. Arrays are commonly used in computer programs to organize data so that a related set of values can be easily sorted or searched.

You can declare an array in 2 ways:

let list1 :number[] = [1,2,3]
let list2: Array<number> = [1,2,3]

String arrays

let list3: Array<string> = ['1','2','3']
let list4: Array<string> = [`1  
${list2}`,'2','3']
console.log(list4)

Image

Any

'any' is used when you are not sure what the data type is. When a variable is declared as “any” it can be assigned any value

let a :any; 
a = "200"; 
a = 200; 
a = false; 
console.log(a)

Tuple

A tuple is an array of fixed length. It allows multiple types in a single array.
let student : [string,number] = ['josh',2]
console.log(student)

Image

Type Inference

Type inference happens in TypeScript when there is no explicit data type specified and the variable is initialized.

The following will work
let a
a = true
a= 1

The following will throw an error since the type is inferred as number;
let a = 10
a = true

Union of Types

TypeScript allows multiple types for a single variable. You can achieve this by using the pipe symbol in the variable declaration. This is normally used when the data stored in the variable is not under your control.

In comparison to “any”, it allows a higher degree of control. It also provides intellisense support.

let a :number|string;
a=20;
a="zoom"

Below is the Intellisense for a when is a union of number and string

Image

Below is the Intellisense when it is any

Image

Functions

In any programming language, functions define how to do things.

1. A simplest function will look like this:

function printHello(){ 
console.log('Hello') 
} 
printHello()

2. A function can receive parameters as below

function printHello(message){ 
console.log(message) 
} 
printHello('hello')

3. Parameter is declared with a type

function printHello(message:string){ 
console.log(message) 
} 
printHello('hello')

4. Multiple Parameters

function printHello(message:string, name:string){ 
console.log(message + " " + name) 
} 
printHello('hello', 'josh')

5. Optional Parameters
Optional parameters are suffixed with a question mark

function printHello(message:string, name?:string){ 
if(name) 
console.log(message + " " + name) 
else 
console.log(message ) 
} 
printHello('hello', 'josh') 
printHello('hello, how are you' )

The output will be

Image

6. Default values for parameters

If a parameter is not passed, it can be initialized with a default value

function printHello(message:string = 'Hello', name?:string){
if(name)
console.log(message + " " + name)
else
console.log(message )
}
printHello()

Image

7. Defining return types

A return type is defined as below

function printHello(message:string, name:string):string{ 
if(name) 
return message + " " + name 
else 
return message  
} 
let message = printHello("Hello", "Josh"); 
console.log(message);

Classes

A class is a template for an object and an object is an instance of a class.

  1. Variables defined within a class are called Instance Variables
  2. Code is contained in Methods
  3. Methods and Variables are called Members
  4. Variables are accessed and acted upon by the methods
  5. Data of one object is separate and unique from any other object

Below is an example of a TypeScript class

class Person{ 
    firstName:string; 
    lastName:string;

    sayHello(){ 
        console.log("hello " + this.firstName) 
    }

sayGoodBye(){ 
        console.log("bye " + this.firstName) 
    } 
}
  1. firstName and lastName are instance variables.
  2. sayHello and sayGoodbye are the methods that contain the code of the class.
  3. firstName, lastName, sayHello() and sayGoodBye() are the members.
  4. The variables are accessed and acted upon by the method;

An instance of the class is created as follows

let max = new Person();
max.firstName = "Max";
max.lastName = "Payne";
max.sayHello();
console.log(max);

Image

Constructors

Constructors are used to initialize classes. They are automatically called when the class is created

class Person{ 
    firstName:string; 
lastName:string;

constructor(firstName:string, lastName?:string){ 
        this.firstName = firstName; 
        this.lastName = lastName; 
    } 
    sayHello(){ 
        console.log("hello " + this.firstName) 
    } 
sayGoodBye(){ 
        console.log("bye " + this.firstName) 
    } 
} 
let max = new Person("Max", "Payne"); 
max.sayHello(); 
console.log(max);

Image

Optional properties

A class can have optional properties as follows

   lastName?:string; 

Array of objects

Objects arrays can be initialized as follows:

let persons :Person[] =  
[{"firstName":"Quintin","lastName":"Tarantino"}, 
{"firstName":"Steven","lastName":"Spielberg"}, 
{"firstName":"Christopher","lastName":"Nolan"}]

They can be looped through using a for loop as follows

for(let i=0; i<persons.length; i++){ 
    console.log(`${i} ${persons[i].firstName}
${persons[i].lastName}`) 
}

Or using a while loop

let i=0; 
while(i<persons.length){ 
    console.log(`${i} ${persons[i].firstName}
${persons[i].lastName}`) 
    i++; 
}

Interfaces

Interfaces specify “what” a class must do, but not “how”. They define the structure of a class.

interface Person{
    firstName:string;
    lastName:string;
    sayHello();
sayGoodBye();
}
The implementation of sayHello and sayGoodBye is upto the classes that implement the interface to define.

Class SimplePerson implements Person{ 
    firstName:string; 
    lastName:string; 
    sayHello(){ 
console.log(“Simple Hello”; 
    } 
sayGoodBye(){ 
console.log(“Simple Bye”; 
    } 
} 
Class ComplexPerson implements Person{ 
    firstName:string; 
    lastName:string; 
    sayHello(){ 
console.log(“Complex Hello”; 
    } 
sayGoodBye(){ 
console.log(“Complex Bye”; 
    } 
}

Modules

Modules are executed within their own scope, not in the global scope; this means that variables, functions, classes, etc. declared in a module are not visible outside the module unless they are explicitly exported from the module and imported into the program using them.

In the above example, the interface Person will not be accessible unless it is imported.

export interface Person { 
    firstName:string; 
lastName:string; 
sayHello(); 
sayGoodBye(); 
}

The class implementing the interface has to import the module

import { Person } from "./helloInterface"; 
class Person3 implements Person{

The key points to be noted here are the export keyword and import statement

A Note on Compilation

TypeScript applies object oriented programming to JavaScript. The process of conversion of TypeScript to JavaScript is an example of transpilation.

One of the key advantages of transpilation is that it allows us to use future features of JavaScript today.

+91

By Signing up, you agree to ourTerms & Conditionsand ourPrivacy and Policy

Get your free handbook for CSM!!
Recommended Courses