📄 Table of contents

▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬✦✦✦ ▬▬▬▬▬▬▬▬▬▬▬▬▬▬

Introduction

  • TypeScript is object oriented JavaScript. TypeScript supports object-oriented programming features like interfaces, classes, etc.
  • TypeScript files(.ts) on compilation produce JavaScript files(.js) with the same name.

migrate from JS to TS

  1. Add tsconfig.json file to project
  2. Integrate with a build tool using webpack or gulp or grunt or browserify.
  3. Change all .js files to .ts files, Similarly, rename the .jsx file to .tsx.
  4. Check for any errors

Since TypeScript has strict type checking, you may notice errors in your JavaScript code.

Few examples:

a) function with too many or two few arguments

function displayPerson(name, age, height) {
let str1 = "Person named " + name + ", " + age + " years old";
let str2 = (height !== undefined) ? (" and " + height + " feet tall") : '';
console.log(str1 + str2);
}
displayPerson( "John", 32);

In the above code, we have a function named displayPerson() that takes three arguments: name, age, and height. We call the above function with two values: "John", and 23. The above function is perfectly valid with JavaScript. This is because if an expected argument to a function is missing in JavaScript, it assigns the value undefined to the argument.

However, the same code in TypeScript will give the compilation error: error TS2554: Expected 3 arguments, but got 2.

To rectify this, you can add an optional parameter sign to the argument height. Also, while you are removing errors, you can also annotate your code like below:

function displayPerson( name: string, age: number, height?: number) {
let str1: string = "Person named " + name + ", " + age + " years old";
let str2: string = (height !== undefined) ? (" and " + height + " feet tall") : '';

console.log(str1 + str2);
}

b) Consider the following object in JavaScript:

let employee = {};
employee.code = 10;
employee.name = "John";
console.log(employee);

In TypeScript, above would give a compilation error:

error TS2339: Property ‘code’ does not exist on type ‘{}’.

error TS2339: Property ‘name’ does not exist on type ‘{}’.

To rectify this, you can move the properties inside the object:

let employee = {
code: 10,
name: "John"
};

Or, create an interface:

interface Employee {
code: number,
name: string
}
let empObj = {} as Employee;
empObj.code = 10;
empObj.name = "John";

Types

Also, in TypeScript, we have advanced types and in these advanced types, we have something called type aliases. With type aliases, we can create a new name for a type but we don’t define a new type.

Types vs. interfaces

The difference between types and interfaces in TypeScript used to be more clear, but with the latest versions of TypeScript, they’re becoming more similar.

Interfaces are basically a way to describe data shapes, for example, an object.

Type is a definition of a type of data, for example, a union, primitive, intersection, tuple, or any other type.

Declaration merging

Duplicate identifier Song.

Extends and implements

Interfaces can extend classes….like

interface NewCar extends Car {...}

We can also create classes implementing interfaces.

class NewestCar implements NewCar

This is not possible with types though.

Intersection

we can create a new intersection type combining two interfaces, however We cannot create an interface combining two types.

Union

Similar to intersections, we can create a new union type combining two interfaces, for example, but not the other way around.

Tuples

type Reponse = [string, number]

But, in TypeScript, we can only declare tuples using types and not interfaces.

Interfaces

Classes that are derived from an interface must follow the structure provided by their interface.

The TypeScript compiler DOES NOT convert interface to JavaScript. It uses interface for type checking. This is also known as “duck typing” or “structural subtyping”.

An interface is defined with the keyword interface and it can include properties and method declarations using a function or an arrow function.

interface IEmployee {
empCode: number;
empName: string;
getSalary: (number) => number; // arrow function
getManagerName(number): string;
}

Interface in TypeScript can be used to define a type and also to implement it in the class.

An interface can be extended by other interfaces. In other words, an interface can inherit from other interface.

Child_interface_name extends Parent_interface_name

Typescript allows an interface to inherit from multiple interfaces.

Child_interface_name extends Parent1_interface_name, 
Parent2_interface_name,…,ParentN_interface_name

Classes

class Parent {
static num:number; # static variable
str:string = "hello"
private str2:string = "world" # private variable
}

The static keyword can be applied to the data members of a class. A static variable retains its values till the program finishes execution. Static members are referenced by the class name.

The private keyword makes the variable private to the class. It cannot be accessed from the class object directly.

Inheritance can be classified as −

TypeScript supports only single inheritance and multilevel inheritance. It doesn’t support multiple and hybrid inheritance.

  • Single − Every class can at the most extend from one parent class

Method over-riding: Method Overriding is a mechanism by which the child class re-defines the superclass’s method. The super keyword is used(or prefixed) to refer to the immediate parent of a class for accessing parent’s variable, property or method.

super.call_Function_from_parent();

Classes can also implement interfaces.

namespace

A namespace is a way to logically group related code.

namespace SomeNameSpaceName { 
export interface InterfaceName{ }
class ClassName { }
}

The classes or interfaces which should be accessed outside the namespace should be marked with keyword export.

Generic Interface

interface IProcessor<T> 
{
result:T;
process(a: T, b: T) => T;
}
NOTE => Using "T" is a convention but not mandatory ...we can use any other alphabet.

The above IProcessor is a generic interface because we used type variable <T>. The IProcessor interface includes the generic field result and the generic method process() that accepts two generic type parameters and returns a generic type.

As you learned, you can use interface as type. In the same way, generic interface can be used as type, as shown below.

Generic Classes

Example: Generic Class

Copy

class KeyValuePair<T,U>
{
private key: T;
private val: U;
setKeyValue(key: T, val: U): void {
this.key = key;
this.val = val;
}
display():void {
console.log(`Key = ${this.key}, val = ${this.val}`);
}
}
let kvp1 = new KeyValuePair<number, string>();
kvp1.setKeyValue(1, "Steve");
kvp1.display(); //Output: Key = 1, Val = Steve
let kvp2 = new KayValuePair<string, string>();
kvp2.SetKeyValue("CEO", "Bill");
kvp2.display(); //Output: Key = CEO, Val = Bill

Modules

To support loading external JavaScript files, we need a module loader. This will be another js library. For browser (i.e., on the client side) the most common library used is RequieJS. This is an implementation of AMD (Asynchronous Module Definition) specification. Instead of loading files one after the other, AMD can load them all separately, even when they are dependent on each other.

The syntax for declaring an external module is using keyword ‘export’ and ‘import’.

Syntax

//FileName : SomeInterface.ts 
export interface SomeInterface {
//code declarations
}

To use the declared module in another file, an import keyword is used as given below. The file name is only specified no extension used.

import someInterfaceRef = require(“./SomeInterface”);

Experience with Front-end Technologies and MERN / MEAN Stack. Working on all Major UI Frameworks like React, Angular.