Fundamentals Of TypeScript

Points covered

  • What is TypeScript?
  • Why TypeScript?
  • Basic Types, Variable Declarations and Scope
  • Const
  • Functions & Function Parameters
  • Rest Parameter and Spread Operator 

What is TypeScript?

  • TypeScript is an open-source programming language developed and maintained by Microsoft. It is strict syntactical superset of JavaScript.
  • TypeScript is designed for the development of application and transform & compile to JavaScript
  • TypeScript is an object-oriented based on OOPS concept with classes, interfaces and statically typed like Java or C#
  • It was designed by Anders Hejlsberg at Microsoft, who was also designer of C# 
 

Why TypeScript?

  • JavaScript can be used to develop both Client side as well as Server-side applications. Angular, React.js, Backbone.js can be used for Client-side application. Node.js can be used for Server-side application
  • JavaScript is most popular, used programming language with one drawback or limitation that is no type system. Other languages like Java or C# are well structured and strongly typed programming languages.
  • Why we need a Type system? The answer is Type system increase the code quality, readability and maintainability. Most important feature is errors can be occurred and rectified at compile time not at run time
  • The main reason to use TypeScript is to Scale the JavaScript, as without scaling we can not build large and complex applications with the big team working on the same code. That’s why Type system / TypeScript is more important while working on JavaScript projects.

Basic Types

 
Boolean
 
The type which holds true or false value is called Boolean.
  1. let isChecked:Boolean = false;     
Number
 
This type holds the number which can be floating point number, Decimal, Hexadecimal or Octal. 
  1. let a1:number = 45;//Number    
  2. let a2:number = 0x31CF; //hexadecimal    
  3. let a3:number = 0o311; //octal    
  4. let a4:number = 110001; //binary    
  5.     
  6. If we log these variables then we will get below values    
  7.     
  8. console.log(a1); // 45    
  9. console.log(a2); // 12751    
  10. console.log(a3); // 201    
  11. console.log(a4); // 49     
String
 
String is primitive data type that is used to store text type of data, this data can be stored using single or double quotation mark. 
  1. let man1:string = “Virat”    
  2. let country1:string = “India”    
  3. let man1details:string = man1 + “ plays for ” + country1    
Template String
 
TypeScript version 1.4 included support for ES6 Template Strings. Template strings are used to embed expressions into the string. 
  1. let man1details:string = ‘${man1} plays for ${country1}    
Void
 
This type is similar to C# Void, it is used where there is no Datatype. It represents the absence of any type at all. The most common use is the function that does not return anything. It is almost opposite of Any data type. 
  1. let fun(a:number):void{} // This function accept number parameter but return nothing    
Any
 
This type is used to store any type of data. Many times, we don’t know the type of data coming from third-party API or user can enter anything, in such a situation we can use “any” data type. 
  1. let variable1:any=4;    
  2. variable1=”string data”;    
  3. variable1 = true;    
Array
 
The array is a special type which can be used to store multiple data values in sequential manner using a special syntax. There are two ways to declare array as below. 
  1. let colors:string[] = [‘Black’, ‘White’,’Orange’];    
  2. let colors:Array<string> = [‘Black’, ‘White’,’Orange’];    
Enum
 
It is an addition to the standard set of data types from JavaScript is the enum. Almost same as C#, it is a way of giving more friendly names to sets of numeric values. 
  1. Enum Color{ Red, Green, Blue }    
Tuple
 
A tuple is a special type of array, we can say it heterogeneous array which can hold different type of data, however, it will be known type of data. 
  1. let employees:[number, string] = [1, “Virat”];    
Object
 
object is a type which represents the non-primitive type. 
  1. let x1:object = {prop:0};    
  2. let x2:object = null;    
Never
 
The never type represents the type of variables that never occur. For instance, never is the return type for a function expression or an arrow function expression that always throws an exception or one that never returns. 
  1. function abc():never{  
  2. throw 20;  // throwing a number exception  
  3. while(true){ // control never returns  
  4. }}  

Variable Declarations

  • JavaScript and TypeScript have the same rules of variable declarations. Variables can be declared using let, var and const.
  • Variable which is declared within block inside function with var has function level scope rather than block level scope, because of typescript hosting in the JavaScript
  • Let variable declaration allows to have block level scope to variables declared within the block inside function
Advantages using let vs var
    • Block-scoped let variables cannot be read or written to before they are declared
    • let variables cannot be re-declared
    • Variables declared using ‘let’ minimize the possibilities or runtime errors, as the compiler give compile-time errors. This increases the code readability and maintainability

Const

  • const Variables can be declared using const similar to var or let declarations. The const makes a variable a constant where its value cannot be changed. const variables have the same scoping rules as let variables. 
  • const variables must be declared and initialized in a single statement. Separate declaration and initialization is not supported
  • const variables allow an object sub-properties to be changed but not the object structure
  • let vs const - We have two types of declarations with the similar scope when to use which one really depends.   
  • Applying the principle of least privilege all declarations other than those you plan to modify should use const 

Functions & Function Parameters

 
In TypeScript, functions can be of two types - named and anonymous.
  • Named Functions
    A named function is one where you declare and call a function by its given name. Functions can also include parameter types and return type.

  • Anonymous Function
    An anonymous function is one which is defined as an expression. This expression is stored in a variable. So, the function itself does not have a name. These functions are invoked using the variable name that the function is stored in. Generally Anonymous function is used to pass as a parameter to another function

  • Arrow Function
    Fat arrow notations are used for anonymous functions i.e. for function expressions. They are also called lambda functions in other languages.
    (param1, param2, .... param n)=> expression

  • Function Overloading
    TypeScript provides the concept of function overloading. You can have multiple functions with the same name but different parameter types and return type. However, the number of parameters should be the same.

    Function overloading with different number of parameters and types with same name is not supported

  • Optional Parameters
    TypeScript has an optional paramater functionality. The parameters that may or may not receive a value can be appended with a '?' to mark as optional. All optional parameters must foloow required parameters and should be at the end

  • Default Parameters
    TypeScript provides the option to add default values to parameters. So, if the user does not provide a value to an argument, TypeScript will initilize the parameter with the default value. Default parameters have the same behaviour as optional parameters. If a value is not passed for the default parameter in a function call, the defauld parameter must foloow the required parameters in the function signature.

Rest Parameter

 
When the number of parameters that a function will receive is not known or can vary, we can use rest parameter. In JavaScript, this is achieved with the "arguments" variable. However, with TypeScript, we can use the rest parameter denoted by ellipsis'...'
  • We can pass zero or more arguments to the rest parameter. The compiler will create an array of arguments with the rest parameter name provided by us.
  • Rest parameters must come last in the function definition, otherwise the TypeScript compiler will show an error 
    1. let Greet = (greeting: string, ...names: string[])=>{    
    2. return greeting + " " + names.join(",") + "!";    
    3. }    
    4. Greet("Hello""Virat","Kohli");    
    5.     // returns "Hello Virat, Kohli!"    
    6. Greet("Hello");    
    7.     // returns "Hello !"    

Spread Operator

 
Spreading or elements of an iterable collection as an array into literal elements as well into individual function parameters.
  • With TypeScript, we can use the spread operator denoted by ellipsis '...' same as Rest Parameter.
  • So how do you differentiate, it's a Rest Parameter or Spread Operator?
  •  When ... ellipsis is on the left hand side of the assignemnt operator then it is Rest Operator.
  • When ... ellipsis is on the right hand side of the assignment operator then it is Spread Operator
    1. let arr:number[] = [10,20,30];    
    2. console.log(arr); //[10,20,30] //an array    
    3. console.log(...arr); // 10,20,30 // Individual elements    
 These are some basic concepts in TypeScript. the beginner can start with these concepts so that their concepts get clear.
 
__Happy Coding__ 


Similar Articles
Blue Ocktopus Technology Systems Private Limited
Enabling revenue generation through brand loyalty and customer retention for enterprise retail and e