TYPESCRIPT

Introduction about TypeScript:

  • TypeScript is an open-source programming language developed and maintained by Microsoft. It is a strict syntactical superset of JavaScript, and adds optional static typing to the language.
  • It was first appeared in 2012 with the extension of .ts and .tsx.
  • TypeScript is designed for development of large applications and transpiles to JavaScript.
  • TypeScript may be used to develop JavaScript applications for both client-side and server-side (Node.js) execution.
  • The TypeScript compiler is itself written in TypeScript and compiled to JavaScript.

Why TypeScript is called superset of JavaScript?

  • In general superset refers to the additional strength.
  • Compiler errors is one of the major problems in javascript.
  • One of the possible advantages is that it will give you any error you may have in the     syntax on compile time instead of runtime .
  • Your development becomes more smooth in the long run, the transcompile doesn’t take that long so it shouldn’t be a huge impact in your speed compared to the gains of having the errors show up without having to run the application.

TRANSPILER:

     Transpilers, source-to-source compilers, are tools that read source code written in one programming language, and produce the equivalent code in another language. Languages you write that transpile to JavaScript are often called compile-to-JS languages, and are said to target JavaScript.

Features of TypeScript:

  • TypeScript is just JavaScript: TypeScript starts with JavaScript and ends with JavaScript. Typescript adopts the basic building blocks of your program from JavaScript. Hence, you only need to know JavaScript to use TypeScript. All TypeScript code is converted into its JavaScript equivalent for the purpose of execution.
  • TypeScript supports other JS libraries: Compiled TypeScript can be consumed from any JavaScript code. TypeScript-generated JavaScript can reuse all of the existing JavaScript frameworks, tools, and libraries.
  • JavaScript is TypeScript: This means that any valid .js file can be renamed to .ts and compiled with other TypeScript files.
  • TypeScript is portable: TypeScript is portable across browsers, devices, and operating systems. It can run on any environment that JavaScript runs on. Unlike its counterparts, TypeScript doesn’t need a dedicated VM or a specific runtime environment to execute.

Why we use TypeScript in angular?

  • The Angular documentation not only supports TypeScript as a first-class citizen, but uses it as its primary language.
  • Old browsers does not understand ES6, TypeScript is designed to add the new Es6
  • javascript features in the Es5 javascript supported browsers ,by compiling the typescript code(which implements the Es6 features) into Es5 code ,Hence will work with all the browsers.
  • Classes and modules are the two main concepts which are introduced in ES6 that are not directly supported by the browsers. Typescript can compile the code into the right javascript code then it can be supported by the browser.
  • Further typescript checks for types hence can use for bigger code projects with good architecture .

Advantages of using TypeScript:

  • Purely Object Oriented Programming. (Classes, Interfaces, Modules, Namespaces, etc).
  • Typed( Static type checking ).
  • ECMAScript 6 support. ( Learn Future JavaScript in advance )
  • Clean, manageable and maintainable code.
  • Namespacing concept.
  • On top of all it allows us to write code in both (JavaScript and Typescript).

Example with TypeScript:

  1. First create a typescript file,

var name1:string = “john”;

var id:number = 1002;

var married:boolean = true;

A typescript file consist of the variables with types.

  1. After creating the typescript file install the typescript package to transpile the typescript file into the .js file.
  2. For that, open the node “command prompt” to type the command as,

npm install –g typescript

  • npm: is a package manager for node.js. It is an online repository for the publishing of open-source Node.js projects. Command line utility to install Node.js packages, it can do version management and dependency management of Node.js packages.
  • -g: instead of typing as –global we simply type it as –g.
  1. To check the version. Type as,

tsc –v

  • Tsc: acronym for “ typescript compiler “.
  • v: it will shows the current version number of the typescript compiler.
  1. Then go to the specified folder in which the file is located. In that type the command as,

tsc example.ts

  • tsc example.ts: it will compile the example.ts file to generate the

                     example.js file.

  • ·Compile multiple files: we can compile more than one ts file at a time by using the    command,

       tsc file1.ts file2.ts, file 3.ts (multiple files will be generated).

  1. Now go to that editor, and check there will be two files as .ts file and .js files respectively. The .js file will be created automatically because of the node runtime. The process will run in the background.
  2. Difference between .ts file and .js file:
Javascript Typescript
It is a scripting language. It is an object oriented programming language(not pure).
There is no static typing. ex: var & num. Here it is static typing (We can declare a variable in multiple ways). ex: var num : number;.
It doesn’t have interfaces . It has interfaces.
It has no optional parameter feature. It has optional parameter feature.
It has no Rest Parameter feature.

No generics are supported

It has Rest Parameter feature.

Supports generics.

No modules support.

Number, string etc. are the objects.

Supports Modules .

Number, string etc. are the interfaces.

TypeScript Arrays:

Array:

  1. An array is a homogenous collection of values of the same data type. It is a user defined type.
  2. In TypeScript, arrays are themselves a data type, just like number and string. TypeScript provides quite a lot of ways for you to declare an array. But all of the methods give you the same result.

Some features of an Array:

  •  An array declaration allocates sequential memory blocks.
  •  Arrays are static. This means that an array once initialized cannot be resized.
  •  Each memory block represents an array element.
  •  Array elements are identified by a unique integer called as the subscript / index of  the element.
  •  Array element values can be updated or modified but cannot be deleted.

Declaring and Initializing Arrays:

Syntax:

var array_name[: datatype];          //declaration

array_name = [val1, val2, valn]   //initialization

Example:

var myarray:number[ ];

myarray = [1, 2, 3, 4 ]  ;

Difference between array.ts & array.js file:

Generic arrays:

  • Array types can be written in one of two ways. In the first, you use the type of the   elements followed by [ ] to denote an array of that element type.
  • The second way uses a generic array type, Array:
  • var list: Array<number> = [1, 2, 3];

Syntax:

var array_name: Array<data type>=[ ];  //declaration

array_name = [val1, val2, valn]            //initialization

Example:

  • Difference between the .ts and .js files:

Strongly typed array:

  • TypeScript is strongly typed and your knowledge about returning value does not actually matter.
  • It can return variable length array in general thus you must comply and assign its return value to the variable of type .
  • During indexing array you can do whatever you want to, so if you are sure that there are 3 elements you can assign them to the array.

Syntax:

Var array-name : string[ ] = [‘var1’, ‘var2’];

Var array-name : number[ ] = [2, 4, 6]     ;

Example:

  • You can the types declared for the array-name,

Here in this example it is showing the error because type is not matched with  boolean.

  • For that, assign a boolean value to that array.
  • Difference between the .ts and .js file,

ANY [  ]:

  • The any array is used for declaring the array of any types without any restrictions.
  • In default, the array type will take as any.

Syntax:

Var myarray : any[  ] = [ 45, ‘ typescript’, true ];

Example:

  • It can accept any type of data inside the array,
  • Difference between the .ts and .js file,

Tuples:

  • The term tuple originated as an abstraction of the sequence: single, double, triple, quadruple, quintuple, … n-tuple.
  • JavaScript does not have tuples as data types but TypeScript does.
  • In a sense, a tuple is an array, with mixed types and a limited number of items. It can be used as a limited key/value pair representation.
  • When we declare the type as a [string,number] tuple, we are limiting this array to stay within the string/number format.
  • In tuples, order is important. Data needs to be imputed as initially declared.
  • The thing with tuples is that we can assign two data types to an array of two items.

Syntax:

Var array-name [ string, number, boolean ] = [ ‘name’, 30, false ];

Example:

  • Here, in this example you can see the type is wrongly defined. The types should be rightly defined in this array, as they are strongly typed arrays.
  • Difference between the .ts file and .js file,

Arrow Functions

Lovingly called the fat arrow (because -> is a thin arrow and => is a fat arrow) and also called a lambda function (because of other languages). Another commonly used feature is the fat arrow function ()=>something. The motivation for a fat arrow is:

  1. You don’t need to keep typing function
  2. It lexically captures the meaning of this
  3. It lexically captures the meaning of arguments

For a language that claims to be functional, in JavaScript you tend to be typing function quite a lot. The fat arrow makes it simple for you to create a function

Arrow function with parameters but no return value

Following is the syntax of an arrow function having some parameters but returns no value.

(v1: type, v2: type, …): void => {}

Example:ES6

var employees: any[] = [{ name: ‘john’, age: 24 }, { name: ‘kiran’, age: 22 }];

var ageGreaterThan23:any[] = employees.filter(

 (emp)=>{

     return emp.age > 23;

 }

)

console.log(employees);

console.log(ageGreaterThan23);

ECAMASCRIPT COMPARSION ES5 VS ES6  

  1. One arugement one line code
  2. It produce same result no return type no function key ward lesscode
  3. No parathesis  no curley brasses
  4. Easy to write code

ECAMPASCRIPT5:

Example:

var employees = [{ name: ‘ajay’, age: 24 }, { name: ‘kiran’, age: 22 }];

var ageGreaterThan23 = employees.filter(function (emp) {

  return emp.age > 23;

});

console.log(employees);

console.log(ageGreaterThan23);

CLASSES:

  • TypeScript is object oriented JavaScript. TypeScript supports object-oriented programming features like classes, interfaces, etc.
  • A class in terms of OOP is a blueprint for creating objects. A class encapsulates data for the object.
  • Typescript gives built in support for this concept called class.
  • JavaScript ES5 or earlier didn’t support classes.

Syntax:

class class_name {
  //class scope     }

A class definition can include the following,

  1. Fields − A field is any variable declared in a class. Fields represent data pertaining to objects.
  2. Constructors − Responsible for allocating memory for the objects of the class.
  3. Functions − Functions represent actions an object can take. They are also at times referred to as methods.

Example:class student {                               //field
  marks : number ;            
  constructor(marks : number){   //constructor
  this.marks = marks
  }
  disp():void {                                   //function
  console.log(“marks is  : “+this.marks)
  }
  }

this Keyword:

  • The this keyword refers to the current instance of the class.
  • Here, the parameter name and the name of the class’s field are the same.
  • Hence to avoid ambiguity, the class’s field is prefixed with the this keyword.
  • Classes in .ts file is converted into ES5
  • Classes in .ts file is converted into ES6,
  • ES6 supports classes, so it will display the classes in .js file also.

INTERFACES:

  • An interface is a syntactical contract that an entity should conform to. In other words, an interface defines the syntax that any entity must adhere to.
  • Interfaces define properties, methods, and events, which are the members of the interface.
  • Interfaces contain only the declaration of the members. It is the responsibility of the deriving class to define the members. It often helps in providing a standard structure that the deriving classes would follow.
  • TypeScript, interfaces fill the role of naming these types, and are a powerful way of defining contracts within your code as well as contracts with code outside of your project.

Syntax:

interface interface_name  {
}

Example:

  • Here in this example you can see the avatar?: string;  which means that is an optional type variable. You can use it or not it doesn’t matters.
  • Difference between .ts file and .js file.
  • Interfaces are not to be converted to JavaScript. It’s just part of TypeScript. If you see the screenshot of TS there is no javascript emitted when you declare an interface unlike a class. So interfaces have zero runtime JavaScript impact.

Extending interfaces:

  • In typescript, You can extend this simple type system with enumerated values and four kinds of object types: interfaces, classes, arrays and functions.
  • For instance, we have two interfaces named with name interface and address interface. Name interface extends address interface that means that the properties and functions of address interface would also be available to the name interface of address interface.

Syntax:

interface interface2 extends interface1{

}

Example:

  • Difference between .ts file and .js file,
  • Javascript doesn’t understand the interface concept so it will skip the part.

Class implementing interfaces:

  • An interface can be used in a number of scenarios but by far the most common is when used with classes.
  • An interface lets you describe the minimum set of public facing properties or methods that a class has.
  • Another way interfaces are explained is that they describe a set of rules the class has to follow, a contract it has to adhere to.

Syntax:

class interface2 implements interface1 {
}

Example:

  • Here is an example for the bankAccount interface which is implemented by the class SavingsAccount.
  • Difference between the .ts file and .js file,

Modules:

  • In TypeScript, just as in ECMAScript 2015, any file containing a top-level import or export is considered a module. Conversely, a file without any top-level import or export declarations is treated as a script whose contents are available in the global scope.
  • Modules are declarative, the relationships between modules are specified in terms of imports and exports at the file level.
  • 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 using one of the export forms. Conversely, to consume a variable, function, class, interface, etc. exported from a different module, it has to be imported using one of the import forms.
  • Modules are the tool for organizing code, with the native support in node.js.
  • Modules are supported by the browser with the help of module loader.

Module Loader:

  • Modules import one another using a module loader. At runtime the module loader is responsible for locating and executing all dependencies of a module before executing it.
  • Well-known modules loaders used in JavaScript are the CommonJS module loader for Node.js and require.js for Web applications.

Reasons to use Modules:

  1. They are modular ( made from a set of separate parts that can be joined together to form a larger object ).
  2. Maintainable.
  3. Reusable.
  4. Native to Node and ES2015.
  5. Organized simply in files and folders.

Exporting form a module:

  • You can export the modules in two ways, export either in declaration or in  export the statment at the end of the file.
  • Use the export keyword, to export the interfaces, classes, functions, etc.

Export the module thorugh declaration.

export interface student{

name : string ;

}

export class subject implements studen{

subject : string ;

}

export function getstudentmarks(marks : number) : Marks{

Return students marks

}

  • Export the module by statements.

interface student{

name : string ;

}

class subject implements studen{

subject : string ;

}

function getstudentmarks(marks : number) : Marks{

Return students marks

}

export{ student, subject, getstudentmarks }

  • For giving other name to the function modules use as keyword,

export{ getstudentmarks as marks }

Importing modules:

  • Importing is just about as easy as exporting from a module. Importing and exporting declaration is done through using one of the import forms.
  • Import the list of things by using the Import keyword.

Syntax:

import { module1, module2 } from  ‘./ filepath’ ;

import * as module from ‘ ./ filepath’ ;

  • *  for importing entire module

Example:

import {Book} from ‘Book-Class’;class Book2 extends Book {
   constructor(bookId: number, bookAutor: string, bookVersion: number) {
       super(bookId, bookAutor, bookVersion);
   }
   bookfun() {
       console.log(‘show the contents’);
   }
}

  • Using export and import statements,

Function types in typescript:

  • The TypeScript type system pays a lot of love to functions, after all they are the core building blocks of a composable system.