TypeScript is superset of JavaScript.
When a TypeScript code is compiled, it results in a JavaScript code and thus it can run at all
instances where JavaScript can run.
TypeScript can be visualized as a syntactic add-on for JavaScript.
The syntax includes all features of ECMAScript 2015 as well as classes and modules, hence it is
object oriented.
TypeScript is centralized around the experience of static typing for JavaScript development.
In ES5, finding bugs at the time of development converts into nightmare sometimes.
Plethora of functionality like arrow functions, classes, template strings, destructuring,
parameters, iterators, generators, modules, map, set, symbols and promises are added to
Javascript by ES6. These are discussed in detail in ECMAScript2015.
The value of ES6 is in writing Less Code, whereas the value of Typescript is in writing Safe code.
A Type System is a set of rules that assign a property called type to various construct a computer
program consists of, such as variables, expressions, functions or modules. Type checker is responsible
for Type checking. It is a kind of program analyzer verifying the types that are being used in the code.
The sole purpose is to recognize the bugs before the execution of the code.
There are two types of type checking:
Static Type Checking
Dynamic Type Checking
Static Type Checking is done at compile time. The type of variable should be declared before using them.
Examples of programming languages using Static Type Checking are C, C++, JAVA, C#, Fortran, Pascal,
Scala etc.
var n: number; // declaration - required in static type checking
n=5; // definition - can be done later or in declaration
var m=6;
Dynamic Type Checking is done at run time. We do not have to declare the type of variables. The
compiler automatically detects the type. Examples are JavaScript, Python, VBScript etc.
/* JavaScript code */
n=5;
m=6;
sum=n+m;
TypeScript has a distinctive feature of supporting the static typing. It concludes that we can declare the
type of variable/ parameter/ function return.
Static typing finds its use only within TypeScript. When converted to a .js file, it has no more role there.
The main motive is to use it to compile time checking that ensures the right values are passed to each
variable, making sure that the program behavior is same as expected.
In TypeScript, we define a type by just appending the variable name with colon followed by the type
name as shown in below examples:
Defining Variables
var num: number = 3;
TypeScript infers the type with the value with which we would have initialized the variable. If we do not
initialize the variable nor define a type when declaring a variable, TypeScript assigns “any” type to the
variable.
var num = 3; // variable num is of type "number"
var num; // variable num is of type "any"
Defining Arrays
let list: number[] = [1, 2, 3];
Type Annotation - Functions and Objects
Defining Functions
let myAdd = ( x: number , y: number): number => { return x+y; };
// first two "number" defines type for parameters 'x' and 'y'
// third "number" defines `return type` of function
We can define optional parameter by adding “?” so that anyone calling that function may or may
not pass value for that variable. Optional parameters do not exist in JavaScript and hence those will
not be handled.
var addFunction = (n1: number, n2: number, n3?: number) : number => {
//observe "?" in parameter n3
//Optional parameter has to be the last parameter in the list
var sum = addFunction(10, 20); //output: 30
We can define any parameter with a default value, and while calling the function, we are not
required to pass the value of the parameters.
var addFunction = (n1: number, n2: number, n3: number = 30) : number => {
//observe parameter n3 has default value
var sum = addFunction(10, 20); // output: 60
Defining Objects
interface Point2D {
x: number;
y: number;
var point2D: Point2D = { x: 0, y: 10 }
Data Type Classification
In TypeScript, data types can be classified in three ways:
any
It implies that the variable can take any type of value, which denotes a dynamic type.
var value: any = 30; //can take string, number, boolean anything
Built-in
Built-in types in Typescript are number, string, boolean, null, undefined, and void.
var value: string = "john"; //can take only string values
Difference between null and undefined
null - variable is set to an object whose value is undefined (empty)
undefined - variable has no value or object assigned to it.
User-defined
User-defined types include enums, classes, interfaces, arrays etc.
interface ToDo {
name: string;
completed?: boolean;
// ? tells that 'completed' is optional property, user need not give value
let todo: ToDo = {
name: 'some string';
TypeScript with conventional "Hello World" program as shown below.
class Greeter{
greeting : T;
constructor (public greeting : T) { this.greeting = greeting; }
greet() {
return "<h1>" + this.greeting + "</h1>";
var greeter = new Greeter <string>("Hello world");
document.body.innerHTML = greeter.greet();
a function to calculate Volume Of Cuboid and display result in web page.
function volumeOfCuboid(length: number, width: number, height: number){
var volume= length*width*height;
return "Volume of the Cuboid is: " + volume;
document.body.innerHTML = volumeOfCuboid(1,2,3);
Generics
Generics are templates allowing the same function to accept arguments of various different types.
Generics create the components that are capable of working over data of present and future. It gives us
the most dynamic capabilities for developing real time large scale software systems. C# and Java use
generics enabling us to create a component that can work over a variety of types rather than a single
one.
You can implement Generics by writing "T" instead of any specific data type like- number,
boolean etc. as shown below.
function calVolumeCube<T>(side: T): T {
return side*side*side;
To explicitly define type of arguments in function call, you can use <> (angular brackets) as
shown below.
let volume = calVolumeCube <number> (5);
Else compiler will decide the type based on argument you pass as shown below.
let volume = calVolumeCube (5);
"T" is used to capture type sent by user.
Enum is a way to organize set of related values. Enum members have numeric value associated with
them and can be either constant or computed. By default first member of enum is assigned value 0
(zero). Then each subsequent member is assigned value incremented by 1 automatically.
enum CardSuit {
Clubs,
Diamonds,
Hearts,
Spades
}
// Sample usage
var card = CardSuit.Clubs;
// Safety
card = "some string"; // Error : string is not assignable to type CardSuit
There are four main principles to Object Oriented Programming
Encapsulation
Inheritance
Abstraction
Polymorphism.
TypeScript can implement all four of OOPs principles with its smaller and cleaner syntax.
Classes
A Class in terms of OOP is a blueprint for creating objects. It includes: fields, constructor and functions.
We use "new" keyword to initialize the class object. Example:
Class in TypeScript
class Student{
name: string;
var newClassObject = new Student();
newClassObject = {
name: "rajesh";
Compiled Class in JavaScript
var Student = (function () {
function Student() {
return Student;
}());
var newClassObject = new Student();
newClassObject = {
name: "rajesh"
};
Note: Class in TypeScript can be transferred to JavaScript.
We can define the scope of variable inside classes as public or private. It is important to note that
the public or private keywords are only available in TypeScript.
class Student {
private firstName: string; //private members
private lastName: string;
yearOfBirth: number; //Public scope by default
schoolName: string;
city: string;
//Constructor
constructor(firstName: string, lastName: string, schoolName: string, city: string, yearOfBirth: number)
{
this.firstName = firstName;
this.lastName = lastName;
this.yearOfBirth = yearOfBirth;
this.city = city;
this.schoolName = schoolName;
age() {
return 2017 - this.yearOfBirth;
printStudentFullName(): void {
alert(this.lastName + ',' + this.firstName);
Interface
Interface helps in detecting error in compile time.
interface Volume {
length: number;
width: number;
sayHi: () => string;
//Volume binding object Physics to define all members as specified by interface
var Physics: Volume = {
length: 10,
width: "ten",
sayHi: (): string => { return "Hello" }
JavaScript uses prototypical inheritance instead of classical inheritance.
TypeScript allows us to inherit from existing classes according to need. Here is a code snippet to explain:
class Cube {
length: number;
constructor(length : number) {
this.length = length;
class Physics extends Cube {
color: string;
constructor(length: number, color: string) {
super(length);
this.color = color;
var obj = new Physics(10, "yellow");
s there any overloading in JavaScript?
Yes, function overloading is possible in TypeScript. The following code snippet will demonstrate how:
class Length{
Length(length: number);
Length(length:string);
Length(value: any) {
if (value && typeof value == "number") {
alert("overload 1");
if (value && typeof value == "string") {
alert("overload 2");
}}
Polymorphism - Overriding
Method Overriding is a mechanism by which the child class redefines the superclass’s method.
The following code snippet will demonstrate how:
class PrinterClass {
doPrint():void {
console.log("doPrint() from Parent called…")
class StringPrinter extends PrinterClass {
doPrint():void {
super.doPrint()
console.log("doPrint() is printing a string…")
var obj = new StringPrinter()
obj.doPrint()
Typescript module is all about maintenance of the code as it becomes
more complex by using classes and interfaces. It can further be classified as:
Internal modules
External modules
Logical grouping of classes, interfaces and functions into one unit is named
as namespace.
Modules
Module and namespace is differentiated below:
module Cube{
class property{
whereas namespace as:
namespace Cube{
ECMAScript2016 proposes use of Decorators that are currently available as an experimental feature.
Decorator enables us with feature of adding annotations. It can be activated by enabling
"experimentalDecorators" compiler. Constructor, properties, parameters and methods can be decorated
in TypeScript.
Following is an example of class decorator:
@log
class Physics {
cube: string;
constructor(message: string) {
this.cube = message;
helloPhysics() {
return "Hello! " + this.cube;
Decorators
In the previous code, changing the instance where @log was used just before the method
"helloPhysics()" will result to example of method decorator.
Similarly, parameter delcaration can also have parameter decorator.
For instance, see the below code snippet:
@validate
helloPhysics(@required cube: string) {