Enrolled to Infinite Learning

Wednesday 2 December 2020

TypeScript for Frontend And Backend Developers

 

What to Expect from this Post?

If you are a Javascript developer, or work on any other UI framework/ library, or have an understanding of any of them, this post is for you. This post primarily covers those features of Typescript which are beyond Javascript's capabilities. The only prerequisite for you to learn typescript is basic knowledge of Javascript and fair understanding on OOPs paradigm.


What is TypeScript?


By definition, “TypeScript is JavaScript for application-scale development.”

TypeScript is a strongly typed, object oriented, compiled language. TypeScript is a typed superset of JavaScript compiled to JavaScript. In other words, TypeScript is JavaScript plus some additional features.

The TypeScript compiler (tsc) converts the instructions written in TypeScript to its JavaScript equivalent.

This helps backend developers write front-end code faster. Angular 2+ also utilizes typescript.


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.

Compilation −TypeScript will compile the code and generate compilation errors, if it finds some sort of syntax errors. This helps to highlight errors before the script is run.

Strong Static Typing − JavaScript is not strongly typed. TypeScript comes with an optional static typing and type inference system through the TLS (TypeScript Language Service).

TypeScript supports Object Oriented Programming concepts like classes, interfaces, inheritance, etc.

ES 6 Features- TypeScript includes most features of planned ECMAScript 2015 (ES 6, 7) such as class, interface, Arrow functions, etc.

Better IDE support- The development experience with TypeScript is a great improvement over JavaScript. There is a wide range of IDEs that have excellent support for TypeScript, like Visual Studio & VS code, Atom, Sublime, and IntelliJ/WebStorm.

Strict Null Checking- Errors, like cannot read property ‘x’ of undefined, is common in JavaScript programming. You can avoid most of these kinds of errors since one cannot use a variable that is not known to the TypeScript compiler.


TypeScript vs JavaScript




JavaScript

TypeScript

LanguageScripting languageObject-oriented programming language
Learning CurveFlexible and easy to learna programmer should have prior scripting knowledge
TypeLightweight, interpreted programming languageStrongly type object-oriented programming language
Client/Server sideBoth client and server-sideSpecially used in client-side
File Extension.js. ts or .tsx
TimeFasterTakes time to compile the code
Data BindingNo concept of types and interfaces availableConcepts like types and interfaces used to describe the data being used.
AnnotationsAnnotations not requiredCode must be annotated constantly to get the most out of TypeScript Features.
SyntaxAll the statements are written within the Script tag.
The browser program starts interpreting all the text between these tags as a script<script>// javascript code</script>
A TypeScript program is composed of:
Modules
Functions
Variables
Statements
Expressions
Comments
Static TypingThere is no concept of Static typing in JavaScriptSupports static typing.
Support for ModulesDoes not support modulesGives support for modules
InterfaceDoes not have an interfaceHas an interface
Optional parameter functionDoes not supportSupports
Prototyping FeatureDoes not have any such featureHas a feature of prototyping
Community of developersAs JavaScript occupies the major chunk of codes, it is widely accepted and used by the programming communityTypeScript is new and has a relatively smaller community base.
Preference to chooseJavaScript is preferable to use in small coding projects.TypeScript is an object-oriented language which makes the code more consistent, clean, simple and reusable. So it is better to use TypeScript for large projects.


How Typescript Works?



TS code->

var num:number = 12;

var str:string = “Hello”;

var alphas:string[];

alphas = ["1","2","3","4"];

On compiling, it will generate the following JavaScript code.

var num = 12;

var str = “Hello”;

var alphas;

alphas = ["1", "2", "3", "4"];

var nums= [1,2,3,3];


How to Install TypeScript?


There are two main ways to install TypeScript tools such as:

  1. Via npm (Node.js Package Manager) command-line tool
    npm install -g typescript
  2. By installing TypeScript via Visual Studio.


Compile and Execute a TypeScript Program


1)    Save the file with .ts extension.

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

     tsc app.ts

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

     node app.js

The TSC generates a JavaScript version of the .ts file passed to it. In other words, the TSC produces an equivalent JavaScript source code from the Typescript file given as an input to it. This process is termed as transpilation.


DataTypes


The Type System in Typescript checks the validity of the supplied values, before they are stored or manipulated by the program. This ensures that the code behaves as expected. It has both, in-built and user-defined data types.


TypeScript Interfaces


Another interesting feature of typescript is its support for 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.

Let’s consider an object −

var person = {

   FirstName:"Tom", 
   LastName:"Hanks", 
   sayHi: ()=>{ return "Hi"} 
};

If we consider the signature of the object, it could be −

{ 
   FirstName:string, 
   LastName:string, 
   sayHi()=>string 
}

To reuse the signature across objects we can define it as an interface.

Example: Interface and Objects


interface IPerson {

   firstName:string,

   lastName:string,

   sayHi: ()=>string

}

var customer:IPerson = { 
   firstName:"Tom",
   lastName:"Hanks", 
   sayHi: ():string =>{return "Hi there"} 
} 


The customer object in the example is of the type IPerson.

Interfaces can also be inherited by other interfaces.


Optional Parameters And Default Parameters


Optional parameters can be used when arguments need not be compulsorily passed for a function’s execution.

// Optional Parameters
sayHello(hello?: string) {
    console.log(hello);
}

sayHello(); // Prints 'undefined'

sayHello('world'); // Prints 'world'


Function parameters can also be assigned values by default. However, such parameters can also be explicitly passed values.

// Default Parameters
sayHello(hello: string = 'hello') {
    console.log(hello);
}

sayHello(); // Prints 'hello'

sayHello('world'); // Prints 'world'


Typescript Classes


Typescript is Object Oriented Javascript. It supports classes, with a simple syntax like-

class class_name {

   //class scope

}

A class definition can include constructors, fields, functions.

Example:

class Test {

   //field

   projectName:string;

   //constructor

   constructor(projectName:string) {

      this.projectName = projectName;

   }

   //function

   disp():void {

      console.log("Project Name is  :   "+this.projectName)

   }

}

//creating object

var obj = new Test("Test Automation")


//access the field

console.log("Reading attribute value Project Name as :  "+obj.projectName)


//access the function

obj.disp()


The class Test has a field projectName, of type string, and a method that returns nothing (void). Obj is the class object.

The concept of class inheritance is also supported in Typescript. Syntactically, extends keyword is used for inheritance. Rest of the method remains similar to Javascript.

Syntax-

class child_class_name extends parent_class_name


Other OOPs concepts like method overloading, encapsulation, data hiding are also supported by Typescript.


Classes and Interfaces



Classes can also implement interfaces.

interface ILoan {

   interest:number

}

class AgriLoan implements ILoan {

   interest:number

   rebate:number

   constructor(interest:number,rebate:number) {

      this.interest = interest

      this.rebate = rebate

   }

}

var obj = new AgriLoan(10,1)

console.log("Interest is : "+obj.interest+" Rebate is : "+obj.rebate );


The class AgriLoan implements the interface Loan. Hence, it is now binding on the class to include the property interest as its member.


Namespace


A namespace is a way to logically group related code. This is inbuilt into TypeScript unlike in JavaScript where variables declarations go into a global scope and if multiple JavaScript files are used within same project there will be possibility of overwriting or misconstruing the same variables, which will lead to the “global namespace pollution problem” in JavaScript.


Defining a Namespace


A namespace definition begins with the keyword namespace followed by the namespace name as follows −

namespace SomeNameSpaceName { 
   export interface ISomeInterfaceName {      }  
   export class SomeClassName {      }  
} 

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


Modules


Typescript modules are divided into two categories- Internal and External modules.

Internal Modules are logically grouped classes, interfaces, functions into one unit and can be exported in another module. This logical grouping is named namespace in latest version of TypeScript.

Syntax:

namespace TestModule {

  export function add(x, y) { console.log(x + y);}

}


External modules in TypeScript exist to specify and load dependencies between multiple external js files.

There are two scenarios for loading dependents js files from a single main JavaScript file.

  • Client Side - RequireJs
  • Server Side - NodeJs


Syntax-

Exporting:

//FileName : SomeInterface.ts

export interface SomeInterface {

  //code declarations

}

Importing:

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


End Note


Programmers coming from Object Oriented world will find it easy to use TypeScript. With the knowledge of TypeScript, they can build web applications much faster, as TypeScript has good tooling support.

Let us change our traditional attitude to the construction of programs. Instead of imagining that our main task is to instruct a computer what to to, let us concentrate rather on explaining to human beings what we want a computer to do.
--Donald Knuth

Categories

Agile (1) Angular JS (2) CSS (1) css reset (1) Grunt (1) Jasmine (1) Karma (1) Scrum (1) setup (1) Sprint (1) test cases (1) Typescript (1) UI Automation (1) Webstorm (1)
Disclaimer

The information and images of this blog are sometimes referred from various websites and blogs across the web to provide the best possible content to the reader. The information furnished hereby cannot be used for legal purposes. I will not be liable to you (whether under the law of contact, the law of torts or otherwise) in relation to the contents of, or use of, or otherwise in connection with, this website.