Category: 1. TypeScript

  • Tuples

    At times, there might be a need to store a collection of values of varied types. Arrays will not serve this purpose. TypeScript gives us a data type called tuple that helps to achieve such a purpose.

    It represents a heterogeneous collection of values. In other words, tuples enable storing multiple fields of different types. Tuples can also be passed as parameters to functions.

    Syntax

    We can create a tuple using JavaScripts array syntax:

    const tupleName =[value1, value2, value3,...valueN]

    But we need to declare its type as a tuple.

    const tupleName:[type1, type2, type3,...typeN]=[value1, value2, value3,...valueN]

    For Example

    const myTuple:[number,string]=[10,"Hello"];

    You can define a tuple first and then initialize,

    let myTuple:[number,string];// declaring the tuple
    myTuple =[10,"Hello"];// initializing the tuple

    Make sure, the const tuple declared must be initialized.

    You can also declare an empty tuple in Typescript and choose to initialize it later.

    var myTuple =[]; 
    myTuple[0]=10;
    myTuple[1]="Hello";

    Accessing Values in Tuples

    Tuple values are individually called items. Tuples are index based. This means that items in a tuple can be accessed using their corresponding numeric index. Tuple items index starts from zero and extends up to n-1(where n is the tuples size).

    Syntax

    Following is the syntax to access the values in a tuple using its index −

    tupleName[index]

    Example: Simple Tuple

    Open Compiler

    var myTuple:[number,string]=[10,"Hello"];//create a tuple console.log(myTuple[0])console.log(myTuple[1])

    In the above example, a tuple, myTuple, is declared. The tuple contains values of numeric and string types respectively.

    On compiling, it will generate the following code in JavaScript.

    var myTuple =[10,"Hello"];//create a tuple 
    console.log(myTuple[0]);
    console.log(myTuple[1]);

    Its output is as follows −

    10 
    Hello
    

    Example: Empty Tuple

    We can declare an empty tuple as follows and then initialize it.

    Open Compiler

    var tup =[] 
    tup[0]=12 
    tup[1]=23console.log(tup[0])console.log(tup[1])

    On compiling, it will generate the same code in JavaScript.

    Its output is as follows −

    12 
    23 
    

    Tuple Operations

    Tuples in TypeScript supports various operations like pushing a new item, removing an item from the tuple, etc.

    Example

    Open Compiler

    var myTuple:[number,string,string,string]; 
    myTuple =[10,"Hello","World","typeScript"];console.log("Items before push "+ myTuple.length)
    
    myTuple.push(12)// append value to the tuple console.log("Items after push "+ myTuple.length)console.log("Items before pop "+ myTuple.length)// removes and returns the last itemconsole.log(myTuple.pop()+" popped from the tuple")console.log("Items after pop "+ myTuple.length)
    • The push() appends an item to the tuple
    • The pop() removes and returns the last value in the tuple

    On compiling, it will generate the following code in JavaScript.

    var myTuple;
    myTuple =[10,"Hello","World","typeScript"];
    console.log("Items before push "+ myTuple.length);
    myTuple.push(12);// append value to the tuple 
    console.log("Items after push "+ myTuple.length);
    console.log("Items before pop "+ myTuple.length);// removes and returns the last item
    console.log(myTuple.pop()+" popped from the tuple"); 
    console.log("Items after pop "+ myTuple.length);

    The output of the above code is as follows −

    Items before push 4 
    Items after push 5 
    Items before pop 5 
    12 popped from the tuple 
    Items after pop 4
    

    Updating Tuples

    Tuples are mutable which means you can update or change the values of tuple elements.

    Example

    Open Compiler

    var myTuple:[number,string,string,string];// define tuple
    myTuple =[10,"Hello","World","typeScript"];// initialize tupleconsole.log("Tuple value at index 0 "+ myTuple[0])//update a tuple element 
    myTuple[0]=121console.log("Tuple value at index 0 changed to   "+ myTuple[0])

    On compiling, it will generate the following code in JavaScript.

    var myTuple;// define tuple
    myTuple =[10,"Hello","World","typeScript"];// initialize tuple
    console.log("Tuple value at index 0 "+ myTuple[0]);//update a tuple element 
    myTuple[0]=121;
    console.log("Tuple value at index 0 changed to   "+ myTuple[0]);

    The output of the above code is as follows −

    Tuple value at index 0 10 
    Tuple value at index 0 changed to 121
    

    Destructuring a Tuple

    Destructuring refers to breaking up the structure of an entity. TypeScript supports destructuring when used in the context of a tuple.

    Example

    Open Compiler

    var a:[number,string]=[10,"hello"];var[b, c]= a;console.log( b );console.log( c );

    On compiling, it will generate following JavaScript code.

    var a =[10,"hello"];var b = a[0], c = a[1];
    console.log(b);
    console.log(c);

    Its output is as follows −

    10
    hello 
    

    Function Parameters and Tuple Types

    We can define a function to accept explicitly a tuple type. So while calling the function we pass the tuple as argument.

    Example

    Open Compiler

    functionprocessData(data:[string,number]):void{const[name, age]= data;console.log(Name: ${name}, Age: ${age});}let data:[string,number]=["John",32]processData(data);

    We defined here a function processData() that accepts a parameter of tuple type. Inside the function we use tuple destructuring to get the constituent elements. We call the function passing a tuple as argument.

    On compiling, it will generate the following JavaScript code.

    functionprocessData(data){const[name, age]= data;
    
    console.log(Name: ${name}, Age: ${age});}let data =&#91;"John",32];processData(data);</code></pre>

    The output of the above code is as follows −

    Name: John, Age: 32
    
  • Arrays

    The use of variables to store values poses the following limitations −

    • Variables are scalar in nature. In other words, a variable declaration can only contain a single at a time. This means that to store n values in a program n variable declarations will be needed. Hence, the use of variables is not feasible when one needs to store a larger collection of values.
    • Variables in a program are allocated memory in random order, thereby making it difficult to retrieve/read the values in the order of their declaration.

    TypeScript introduces the concept of arrays to tackle the same. An array is a homogenous collection of values. To simplify, an array is a collection of values of the same data type. It is a user defined type.

    Features of an Array

    Here is a list of the 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.
    • Like variables, arrays too, should be declared before they are used. Use the var keyword to declare an array.
    • Array initialization refers to populating the array elements.
    • Array element values can be updated or modified but cannot be deleted.

    Declaring and Initializing Arrays

    To declare an initialize an array in Typescript use the following syntax −

    Syntax

    var array_name[:datatype];        //declaration 
    array_name = [val1,val2,valn..]   //initialization
    

    An array declaration without the data type is deemed to be of the type any. The type of such an array is inferred from the data type of the arrays first element during initialization.

    For example, a declaration like − var numlist:number[] = [2,4,6,8] will create an array as given below −

    Declaring and Initializing Arrays

    The array pointer refers to the first element by default.

    Arrays may be declared and initialized in a single statement. The syntax for the same is −

    var array_name[:data type] = [val1,val2valn]
    

    Note − The pair of [] is called the dimension of the array.

    Accessing Array Elements

    The array name followed by the subscript is used refer to an array element. Its syntax is as follows −

    array_name[subscript] = value
    

    Example: Simple Array

    Open Compiler

    var alphas:string[]; 
    alphas =["1","2","3","4"]console.log(alphas[0]);console.log(alphas[1]);

    On compiling, it will generate following JavaScript code −

    var alphas;
    alphas =["1","2","3","4"];console.log(alphas[0]);console.log(alphas[1]);

    The output of the above code is as follows −

    1 
    2 
    

    Example: Single statement declaration and initialization

    Open Compiler

    var nums:number[]=[1,2,3,3]console.log(nums[0]);console.log(nums[1]);console.log(nums[2]);console.log(nums[3]);

    On compiling, it will generate following JavaScript code −

    var nums =[1,2,3,3];console.log(nums[0]);console.log(nums[1]);console.log(nums[2]);console.log(nums[3]);

    Its output is as follows −

    1 
    2 
    3 
    3 
    

    Array Object

    An array can also be created using the Array object. The Array constructor can be passed.

    • A numeric value that represents the size of the array or
    • A list of comma separated values.

    The following example shows how to create an array using this method.

    Example

    Open Compiler

    var arr_names:number[]=newArray(4)for(var i =0;i<arr_names.length;i++){ 
       arr_names[i]= i *2console.log(arr_names[i])}

    On compiling, it will generate following JavaScript code.

    var arr_names =newArray(4);for(var i =0; i < arr_names.length; i++){
       arr_names[i]= i *2;console.log(arr_names[i]);}

    Its output is as follows −

    0 
    2 
    4 
    6 
    

    Example: Array Constructor accepts comma separated values

    Open Compiler

    var names:string[]=newArray("Mary","Tom","Jack","Jill")for(var i =0;i<names.length;i++){console.log(names[i])}

    On compiling, it will generate following JavaScript code −

    var names =newArray("Mary","Tom","Jack","Jill");for(var i =0; i < names.length; i++){console.log(names[i]);}

    Its output is as follows −

    Mary 
    Tom 
    Jack 
    Jill
    

    Array Methods

    A list of the methods of the Array object along with their description is given below.

    S.No.Method & Description
    1.concat()Returns a new array comprised of this array joined with other array(s) and/or value(s).
    2.every()Returns true if every element in this array satisfies the provided testing function.
    3.filter()Creates a new array with all of the elements of this array for which the provided filtering function returns true.
    4.forEach()Calls a function for each element in the array.
    5.indexOf()Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found.
    6.join()Joins all elements of an array into a string.
    7.lastIndexOf()Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found.
    8.map()Creates a new array with the results of calling a provided function on every element in this array.
    9.pop()Removes the last element from an array and returns that element.
    10.push()Adds one or more elements to the end of an array and returns the new length of the array.
    11.reduce()Apply a function simultaneously against two values of the array (from left-to-right) as to reduce it to a single value.
    12.reduceRight()Apply a function simultaneously against two values of the array (from right-to-left) as to reduce it to a single value.
    13.reverse()Reverses the order of the elements of an array — the first becomes the last, and the last becomes the first.
    14.shift()Removes the first element from an array and returns that element.
    15.slice()Extracts a section of an array and returns a new array.
    16.some()Returns true if at least one element in this array satisfies the provided testing function.
    17.sort()Sorts the elements of an array.
    18.splice()Adds and/or removes elements from an array.
    19.toString()Returns a string representing the array and its elements.
    20.unshift()Adds one or more elements to the front of an array and returns the new length of the array.

    Array Destructuring

    Refers to breaking up the structure of an entity. TypeScript supports destructuring when used in the context of an array.

    Example

    Open Compiler

    var arr:number[]=[12,13]var[x,y]= arr 
    console.log(x)console.log(y)

    On compiling, it will generate following JavaScript code.

    var arr =[12,13];var x = arr[0], y = arr[1];console.log(x);console.log(y);

    Its output is as follows −

    12 
    13
    

    Array Traversal using forin loop

    One can use the forin loop to traverse through an array.

    Open Compiler

    var j:any;var nums:number[]=[1001,1002,1003,1004]for(j in nums){console.log(nums[j])}

    The loop performs an index based array traversal.

    On compiling, it will generate following JavaScript code.

    var j;var nums =[1001,1002,1003,1004];for(j in nums){console.log(nums[j]);}

    The output of the above code is given below −

    1001 
    1002 
    1003 
    1004
    

    Arrays in TypeScript

    TypeScript supports the following concepts in arrays −

    S.No.Concept & Description
    1.Multi-dimensional arraysTypeScript supports multidimensional arrays. The simplest form of the multidimensional array is the twodimensional array.
    2.Passing arrays to functionsYou can pass to the function a pointer to an array by specifying the array’s name without an index.
    3.Return array from functionsAllows a function to return an array
  • Boolean

    The TypeScript Boolean types represent logical values like true or false. Logical values are used to control the flow of the execution within the program. As JavaScript offers both Boolean primitive and object types, TypeScript adds a type annotation. We can create a boolean primitive as well boolean object.

    We can create a boolean object by using the Boolean() constructor with new keyword.

    To convert a non-boolean value to boolean we should use Boolean() function or double NOT (!!) operator. We should not use Boolean constructor with new keyword.

    Syntax

    To declare a boolean value (primitive) in TypeScript we can use keyword “boolean”.

    let varName:boolean=true;

    In the above syntax, we declare a boolean variable varName and assign the value true.

    To create a Boolean object we use the Boolean() constructor with new Keyword.

    const varName =newBoolean(value);

    In the above syntax, the value is an expression to be converted to Boolean object. The Boolean() constructor with new returns an object containing the boolean value.

    For example,

    const isTrue =newBoolean(true);

    In the above example, isTrue holds value true while isFalse holds the value false.

    Type Annotations

    The type annotations in TypeScript is optional as TypeScript can infer the types of the variable automatically. We can use the boolean keyword to annotate the types of boolean variables.

    let isPresent :boolean=true;// with type annotationlet isPresent =true// without type annotation

    Like variables, the function parameters and return type can also be annotated.

    Truthy and Falsy Values

    In TypeScript, falsy values are the values that are evaluated to false. There are six falsy values

    • false
    • 0 (zero)
    • Empty string (“”)
    • null
    • undefined
    • NaN

    The all other values are truthy.

    Converting a non-boolean value to boolean

    All the above discussed falsy values are converted to false and truthy values are converted to true. To convert a non-boolean value to boolean, we can use the Boolean() function and double NOT (!!) operator.

    Using the Boolean() Function

    The Boolean() function in TypeScript converts a non-boolean value to boolean. It returns a primitive boolean value.

    let varName =Boolean(value);

    The value is an expression to be converted to boolean.

    Example

    In the below example, we use the Boolean() function to convert a non-boolean value to boolean.

    Open Compiler

    const myBoolean1 =Boolean(10);console.log(myBoolean1);// trueconst myBoolean2 =Boolean("");console.log(myBoolean2);// false

    On compiling, the above code will produce the same code in JavaScript. On executing the JavaScript code will produce the following output

    true
    false
    

    Using Double NOT (!!) Operator

    The double NOT (!!)operator in TypeScript converts a non-boolean value to boolean. It returns a primitive boolean value.

    let varName =!!(value);

    The value is an expression to be converted to boolean.

    Example

    In the below example, we use the double NOT (!!) operator to convert a non-boolean value to boolean.

    Open Compiler

    const myBoolean1 =!!(10);console.log(myBoolean1);// trueconst myBoolean2 =!!("");console.log(myBoolean2);// false

    On compiling, the above code will produce the same code in JavaScript. On executing the JavaScript code will produce the following output

    true
    false
    

    Boolean Operations

    The boolean operations or logical operations in TypeScript can be performed using the three logical operators, logical AND, OR and NOT operators. These operations return a boolean value (true or false).

    Example: Logical AND (&&)

    In the example below, we defined two boolean variables x and y. Then perform the logical AND (&&) of these variables.

    Open Compiler

    let x:boolean=true;let y:boolean=false;let result:boolean= x && y;console.log(result);// Output: false

    On compiling, it will generate the following JavaScript code.

    var x =true;var y =false;var result = x && y;console.log(result);// Output: false

    The output of the above example code is as follows

    false
    

    Example: Logical OR (||)

    In the example below, we perform logical OR (||) operation of the two boolean variables x and y.

    Open Compiler

    let x:boolean=true;let y:boolean=false;let result:boolean= x || y;console.log(result);// Output: true

    On compiling, it will generate the following JavaScript code.

    var x =true;var y =false;var result = x || y;console.log(result);// Output: true

    The output of the above example code is as follows

    true
    

    Example: Logical NOT (!)

    The logical NOT (!) operation of the boolean variable isPresent is performed in the below example.

    Open Compiler

    let isPresent:boolean=false;let isAbsent:boolean=!isPresent;console.log(isAbsent);// Output: true

    On compiling, it will generate the same code in JavaScript.

    The output of the above example code is as follows

    true
    

    Conditional Expression with Booleans

    Example: If statement

    The below example shows how to use the conditional expression with boolean in if else statement.

    Open Compiler

    let age:number=25;let isAdult:boolean= age >=18;if(isAdult){console.log('You are an adult.');}else{console.log('You are not an adult.');}

    On compiling it will generate the following JavaScript code

    let age =25;let isAdult = age >=18;if(isAdult){
    
    console.log('You are an adult.');}else{
    console.log('You are not an adult.');}</code></pre>

    The output of the above example code is as follows

    You are an adult.
    

    Example: Conditional Statement (Ternary Operator)

    Try the following example

    Open Compiler

    let score:number=80;let isPassing:boolean= score >=70;let result:string= isPassing ?'Pass':'Fail';console.log(result);// Output: Pass

    On compiling, it will generate the following JavaScript code

    let score =80;let isPassing = score >=70;let result = isPassing ?'Pass':'Fail';
    console.log(result);// Output: Pass

    The output of the above example code is as follows

    Pass
    

    TypeScript Boolean vs boolean

    The Boolean is not same as the boolean type. The Boolean does not refer to the primitive value. Whereas the boolean is primitive data type in TypeScript. You should always use the boolean with lowercase.

    Boolean Objects

    As we have seen above, we can create a Boolean object consisting boolean value using the Boolean constructor with new keyword. The Boolean wrapper class provides us with different properties and methods to work with boolean values.

    Boolean Properties

    Here is a list of the properties of Boolean object

    Sr.No.Property & Description
    1constructorReturns a reference to the Boolean function that created the object.
    2prototypeThe prototype property allows you to add properties and methods to an object.

    In the following sections, we will have a few examples to illustrate the properties of Boolean object.

    Boolean Methods

    Here is a list of the methods of Boolean object and their description.

    Sr.No.Method & Description
    1toSource()Returns a string containing the source of the Boolean object; you can use this string to create an equivalent object.
    2toString()Returns a string of either "true" or "false" depending upon the value of the object.
    3valueOf()Returns the primitive value of the Boolean object.
  • Strings

    In TypeScript, a string represents a sequence of characters. The string type is a fundamental data type in TypeScript. Strings are important to hold data that can be represented in text form. Like JavaScript, TypeScript also supports both string primitives and String objects.

    The String object lets you work with a series of characters. It wraps the string primitive data type with a number of helper methods.

    You can invoke methods on primitive strings because TypeScript automatically wraps the string primitive and call the methods on wrapper object. The same applies to properties also.

    Creating Strings

    Strings in TypeScript can be created as primitives from string literals or as objects using the String() constructor.

    You can use the following syntax to create a String object in TypeScript −

    cost str =newString(value);

    Here str is the newly created String object and value is a series of characters.

    You can create string primitives using single quote, double quotes and backtick.

    let str1:string='a string primitive';let str2:string="another string";let str3:string=yet another string;

    The string primitives can also be created using the String() function without new keyword.

    let str:string=String(value);

    ‘string’ is a primitive, but ‘String’ is a wrapper object. Prefer using ‘string’ when possible.

    String Properties

    A list of the methods available in String object along with their description is given below −

    S.No.Property & Description
    1.ConstructorReturns a reference to the String function that created the object.
    2.LengthReturns the length of the string.
    3.PrototypeThe prototype property allows you to add properties and methods to an object.

    String Methods

    A list of the methods available in String object along with their description is given below −

    S.No.Method & Description
    1.charAt()Returns the character at the specified index.
    2.charCodeAt()Returns a number indicating the Unicode value of the character at the given index.
    3.concat()Combines the text of two strings and returns a new string.
    4.indexOf()Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found.
    5.lastIndexOf()Returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found.
    6.localeCompare()Returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.
    7.match()Used to match a regular expression against a string.
    8.replace()Used to find a match between a regular expression and a string, and to replace the matched substring with a new substring.
    9.search()Executes the search for a match between a regular expression and a specified string.
    10.slice()Extracts a section of a string and returns a new string.
    11.split()Splits a String object into an array of strings by separating the string into substrings.
    12.substr()Returns the characters in a string beginning at the specified location through the specified number of characters.
    13.substring()Returns the characters in a string between two indexes into the string.
    14.toLocaleLowerCase()The characters within a string are converted to lower case while respecting the current locale.
    15.toLocaleUpperCase()The characters within a string are converted to upper case while respecting the current locale.
    16.toLowerCase()Returns the calling string value converted to lower case.
    17.toString()Returns a string representing the specified object.
    18.toUpperCase()Returns the calling string value converted to uppercase.
    19.valueOf()Returns the primitive value of the specified object.

    Examples

    Lets understand the string types with the help of some examples in TypeScript.

    Example: Creating String Primitives

    In the example below, we use single quote, double quote and backtick to create the primitive strings str1, str2 and str3 respectively.

    Open Compiler

    let str1:string='a string primitive';console.log(str1);let str2:string="another string";console.log(str2);let str3:string=yet another string;console.log(str3);

    On compiling, it will generate the following JavaScript code.

    let str1 ='a string primitive';
    console.log(str1);let str2 ="another string";
    console.log(str2);let str3 =yet another string;
    console.log(str3);

    The output of the above example code is as follows −

    a string primitive
    another string
    yet another string
    

    Example: Creating String Objects

    Here we create a String object using the String() constructor with new keyword.

    Open Compiler

    const email =newString('[email protected]');console.log(email);console.log(typeof email);

    On compiling, it will generate the following JavaScript code.

    const email =newString('[email protected]');
    console.log(email);
    console.log(typeof email);

    The output of the above example code is as follows −

    [email protected]
    object
    

    Example: Concatenating TypeScript strings

    To concatenate two string, we can use + operator. Here, we concatenate two strings str1 and str2 and display the result in the console.

    Open Compiler

    let str1:string="Hello ";let str2:string="World!";let str3:string= str1 + str2;console.log(str3);

    On compiling, it will generate the following JavaScript code.

    let str1 ="Hello ";let str2 ="World!";let str3 = str1 + str2;
    console.log(str3);

    The output of the above example code is as follows

    Hello World!
    

    Example: Accessing string elements using indexing

    In the example below, we access the string characters from the 1st and 6th indices.

    Open Compiler

    let message:string="Hello World!";console.log("Character at index 1 is => "+ message[1]);console.log("Character at index 6 is => "+ message[6]);

    On compiling, it will generate the following JavaScript code.

    let message ="Hello World!";
    console.log("Character at index 1 is => "+ message[1]);
    console.log("Character at index 6 is => "+ message[6]);

    The output of the above example code is as follows −

    Character at index 1 is => e
    Character at index 6 is => W
    

    Example: String vs. string in TypeScript

    In TypeScript, type ‘String’ is a wrapper object and type ‘string’ is a primitive type. These both types cant be assigned to each other.

    In the example below, we tried to assign a string object to a variable of type string primitive.

    let str:string;
    str =newString('shahid');

    The above example code will show the following error −

    Type 'String' is not assignable to type 'string'.
      'string' is a primitive, but 'String' is a wrapper object. Prefer using 'string' when possible.
    
  • Numbers

    TypeScript like JavaScript supports numeric values as Number objects. A number object converts numeric literal to an instance of the number class. The Number class acts as a wrapper and enables manipulation of numeric literals as they were objects.

    TypeScript number type represents the numeric values. All the numbers are represented as the floating point values. TypeScript also supports the binary, octal and hexadecimal numbers introduced in ECMAScript 2015.

    In TypeScript, we can create a number primitive as well as Number object.

    Syntax

    We can declare a variable of number type using colon (:) after the variable name followed by number −

    let varName:number= value;

    In the above syntax, we declared a variable named varName of number type. Here value is the any numeric value such as decimal, binary, octal or hexadecimal numbers.

    We can create the Number object. To create a Number object we can use the Number() constructor as follows −

    var var_name =newNumber(value)

    In case a non-numeric argument is passed as an argument to the Numbers constructor, it returns NaN (NotaNumber)

    The type ‘Number’ is a wrapper object but type ‘number’ is a primitive. Prefer using ‘number’ when possible. Type ‘Number’ is not assignable to type ‘number’.

    Creating Number Types

    In the below example, we created a variable count of number type. We assigned 10 to the count.

    Open Compiler

    let count:number=10;console.log(count);

    On compiling, it will generate the following JavaScript code.

    let count =10;
    console.log(count);

    The output is as follows −

    10
    

    We can also assign float, binary, octal and hexadecimal values to a variable of number type. Look at the below TypeScript code snippet

    let decNum:number=10.6;// floating point numberlet binNum:number=0b101001;// binary numberlet octNum:number=0o45;// octal numberlet hexNum:number=0x80fd;// hexadecimal number

    Creating Number Object

    Open Compiler

    const count =newNumber(10);
    console.log(count);
    console.log(typeof count);

    On compiling, it will generate the same JavaScript code.

    The output of the above example code is as follows

    [Number: 10]
    Object
    

    Number Properties

    The following table lists a set of properties of the Number object −

    S.No.Property & Description
    1.MAX_VALUEThe largest possible value a number in JavaScript can have 1.7976931348623157E&plus;308.
    2.MIN_VALUEThe smallest possible value a number in JavaScript can have 5E-324.
    3.NaNEqual to a value that is not a number.
    4.NEGATIVE_INFINITYA value that is less than MIN_VALUE.
    5.POSITIVE_INFINITYA value that is greater than MAX_VALUE.
    6.prototypeA static property of the Number object. Use the prototype property to assign new properties and methods to the Number object in the current document.
    7.constructorReturns the function that created this object’s instance. By default, this is the Number object.

    Example

    Open Compiler

    console.log("TypeScript Number Properties: ");console.log("Maximum value that a number variable can hold: "+ Number.MAX_VALUE);console.log("The least value that a number variable can hold: "+ Number.MIN_VALUE);console.log("Value of Negative Infinity: "+ Number.NEGATIVE_INFINITY);console.log("Value of Negative Infinity:"+ Number.POSITIVE_INFINITY);

    On compiling, it will generate the same code in JavaScript.

    Its output is as follows −

    TypeScript Number Properties:  
    Maximum value that a number variable can hold: 1.7976931348623157e+308 
    The least value that a number variable can hold: 5e-324 
    Value of Negative Infinity: -Infinity 
    Value of Negative Infinity:Infinity
    

    Example: NaN

    Open Compiler

    var month =0if( month<=0|| month >12){ 
       month = Number.NaNconsole.log("Month is "+ month)}else{console.log("Value Accepted..")}

    On compiling, it will generate the same code in JavaScript.

    Its output is as follows −

    Month is NaN
    

    Example: prototype

    Open Compiler

    functionemployee(id:number,name:string){this.id = id 
       this.name = name 
    }var emp =newemployee(123,"Smith") 
    employee.prototype.email ="[email protected]"console.log("Employee's Id: "+emp.id)console.log("Employee's name: "+emp.name)console.log("Employee's Email ID: "+emp.email)

    On compiling, it will generate the following JavaScript code −

    //Generated by typescript 1.8.10functionemployee(id, name){this.id = id;this.name = name;}var emp =newemployee(123,"Smith");
    employee.prototype.email ="[email protected]";
    
    console.log("Employee 's Id: "+ emp.id);
    console.log("Employee's name: "+ emp.name);
    console.log("Employee's Email ID: "+ emp.email);

    Its output is as follows −

    Employee's Id: 123 
    Emaployee's name: Smith 
    Employee's Email ID: [email protected]
    

    Number Methods

    The Number object contains only the default methods that are a part of every object’s definition. Some of the commonly used methods are listed below −

    S.No.Methods & Description
    1.toExponential()Forces a number to display in exponential notation, even if the number is in the range in which JavaScript normally uses standard notation.
    2.toFixed()Formats a number with a specific number of digits to the right of the decimal.
    3.toLocaleString()Returns a string value version of the current number in a format that may vary according to a browser’s local settings.
    4.toPrecision()Defines how many total digits (including digits to the left and right of the decimal) to display of a number. A negative precision will throw an error.
    5.toString()Returns the string representation of the number’s value. The function is passed the radix, an integer between 2 and 36 specifying the base to use for representing numeric values.
    6.valueOf()Returns the number’s primitive value.
  • Type Inference

    Type inference is a feature in TypeScript that allows the compiler to automatically determine (infer) the type of a variable, function or expression. TypeScript is an optionally static type programming language. You can declare variables, expressions, or functions without explicitly annotating their types. The compiler will automatically determine the types at the compile time.

    The type inference can be done on the basis of a number of factors, including

    • The type of values assigned to the variables.
    • The type of function parameters or arguments passed to the function.
    • The type of return value of the function.
    • The types of the object and properties.

    Let’s take a simple example as follows

    let x =5;let y ="Hello World!";

    In the above code, the TypeScript compiler can infer that the type of variable x is number. This is because the variable x is being assigned a number. The compiler can also infer the type of y is string because the y is being assigned a string.

    In the above example, TypeScript automatically infers the types of variables based on the values assigned to them.

    Variable or Member Initialization

    The type inference can be inferred using the variable and member initialization. The TypeScript compiler infers the type of the variable from the initialized value.

    Example

    Let’s take an example of variable initialization as follows

    Open Compiler

    let x =20;let y ="Hello World!";let z =true;console.log("type of x: ",typeof x);console.log("type of y: ",typeof y);console.log("type of z: ",typeof z);

    On compilation, it will generate the same JavaScript code.

    The output of the above example code is as follows

    type of x:  number
    type of y:  string
    type of z:  boolean
    

    Lets have an example of object member initialization

    Open Compiler

    classPerson{
      name ="Shahid";
      age =35;}const p =newPerson();// Prints name and ageconsole.log(${p.name}, ${p.age});

    On compilation, it will generate following JavaScript code.

    classPerson{constructor(){this.name ="Shahid";this.age =35;}}const p =newPerson();// Prints name and ageconsole.log(${p.name}, ${p.age});

    The output of the above code is as follows

    Shahid, 35
    

    Function Default Parameter

    The typescript compiler can also infer the type of the function parameters when the parameters are initialized with default values.

    In the below example, the parameters x and y are initialized with default values. The compiler infers the type of x and y as number. This is because the initialized values are numbers.

    Open Compiler

    functionadd(x =10, y =30){return x + y;}let res =add(2,3);console.log(res);

    On compilation, it will generate the same code in JavaScript.

    The output of the above example code is as follows

    5
    

    Now let’s try to pass arguments as string values.

    let res2 =add('2','3');

    The type of the parameters of the function add are inferred as number so when we pass arguments of type string to the function, it shows the following error

    Argument of type 'string' is not assignable to parameter of type 'number'.
    

    Function Return Type

    The TypeScript compiler infers the type of the return type of the function based on the type of the return value.

    If the function doesn’t return any value, then the return type is void.

    In the example below, the function add accepts the two numbers and return their sum. As the sum of two numbers are number, so the type of return value is number. Hence the compiler infers the return type of the function add as number.

    Open Compiler

    functionadd(x:number, y:number){return x + y;}let res1:number=add(2,3);console.log(res1);

    When we assign the return value of the function add to variable (res2) of type string, it will show an error.

    let res2:string=add(2,3);

    The error is as follows

    Type 'number' is not assignable to type 'string'.
    

    This is because the return type of the function add is number and we are assigning it to variable of string type.

    Best Common Type: The Union Type

    Type inference with variable initialization, function default parameters and return type is straightforward.

    When TypeScript infers a type from multiple expressions, the type of the expressions is determined as the “best common type”.

    Let’s understand this with the help of an example

    const a =[5,10,"TypeScript"];

    In the above example, the array contains values 5, 10, and “TypeScript”. To infer the type of the array, we must consider the type of each element. Here, we have choices for the type of the array as number, and string. The inferred type of the array should be the best common type for each value in the array.

    The best common type has to be chosen from the provided candidate type. If there is no super type of all candidate types, the union type is used. Hence the inferred type of the above array is

    (number | string)[]
    

    The above array can contain values of types number, and string only. If you try to add a value of type different from number and string, it will show an error.

    Let’s try to add a boolean value to the array.

    const a =[5,10,"TypeScript"];
    a.push(true);

    The above code will show the following compilation error

    Argument of type ‘boolean’ is not assignable to parameter of type ‘string | number’.

    Contextual Typing

    Contextual typing is a feature in TypeScript that allows the compiler to infer the type of variable, parameter or expression based on the context where they are used. For example,

    Open Compiler

    window.onmousedown=function(mouseEvent){console.log(mouseEvent.button);}

    In the above example, the TypeScript infers the type the function expression on right hand side of the assignment using the type of the Window.onmousedown function. So it is able to infer the type of mouseEvent parameter as MouseEvent. This way TypeScript infers that mouseEvent has a button property and doesn’t show a compilation error.

    Contextual typing is very helpful in writing concise code without losing type safety.

  •  Type Annotations

    Type Annotations

    In TypeScript,type annotations offer a way to define (or annotate) the data types of variables, class members, function parameters and return values.

    TypeScript is a statically typed programming language that optionally supports the dynamic typing. Because of this support any JavaScript file (.js) can be directly renamed as a TypeScript file (.ts). As we know JavaScript is a dynamically typed programming language and TypeScript is the superset of the JavaScript. TypeScript supports all the functionalities of JavaScript plus some additional features.

    TypeScript provides the way how to annotate the datatype. By the term “type annotations” means assigning the datatypes.

    Variable Type Annotations

    TypeScript supports static typing of variables. We can annotate the types of variables while declaring them. Also TypeScript optionally support the dynamic typing as JavaScript.

    For example, when we define a variable that holds a number, we can define it as follows –

    var x =10;

    The above declaration is absolutely permissible in TypeScript as it supports the dynamic typing.

    We can annotate the datatype of the variable x as follows

    var x:number=10;

    To do a type annotation, you can use colon (:) sign after the variable name followed by datatype of the variable.

    var varName: datatype
    

    Followings are the different examples to annotate a variable with different datatypes.

    let name:string;let age:number;let isEnrolled:boolean;

    In the example above, we added string as type of variable name. Similarly, age and isEnrolled are annotated with number and boolean type.

    Example

    Let’s try the following example. In this example, we have declared two variables, pName, and pAge. We have annotated pName as string and pAge as number.

    Open Compiler

    let pName:string;let pAge:number;
    pName ="John Doe";
    pAge =35;console.log(Name of the person is ${pName} and his age is ${pAge});

    On compiling, TypeScript compiler will produce the following JavaScript code

    let pName;let pAge;
    pName ="John Doe";
    pAge =35;
    console.log(Name of the person is ${pName} and his age is ${pAge});

    The output of the above JavaScript code is as follows

    Name of the person is John Doe and his age is 35
    

    Function Type Annotations

    You can add the type to a function in TypeScript. A function’s type has two parts the function parameters and the return type of the function.

    Function Parameter Type Annotation

    We can annotate the datatypes of the parameters in the function definition.

    Open Compiler

    functiondisplayDetails(id:number, name:string){console.log("ID:", id);console.log("Name", name);}displayDetails(123,"John");

    On compiling, it will produce the following JavaScript code

    functiondisplayDetails(id, name){
    
    console.log("ID:", id);
    console.log("Name:", name);}displayDetails(123,"John");</code></pre>

    The result of the above example code is as follows

    ID: 123
    Name: John
    

    Function Return Type Annotation

    You can add the datatype of the function return. It will be the datatype of the value returned by the function.

    functionadd(x:number, y:number):number{return x + y;}

    If you are not writing a return type then, the default return type of any function will be undefined.

    If a function is not returning any value then, you should use void as function return type instead of leaving it off.

    For example, instead of writing the following

    functiongreet(name:string){console.log(Hello Mr. ${name}. Welcome to Tutorials Point.);}

    Write the function using void as return type as follows

    functiongreet(name:string):void{console.log(Hello Mr. ${name}. Welcome to Tutorials Point.);}

    Example

    In the example below, we annotate the function parameters and its return type. The function add take two parameters - x and, y of number type and also a value of number type. The returned value is the sum of the passed arguments to the function.

    Open Compiler

    functionadd(x:number, y:number):number{return x + y;}console.log(add(2,3))

    On compiling, it will produce the following JavaScript code

    functionadd(x, y){return x + y;}
    console.log(add(2,3));

    The output of the above code is as follows −

    5
    

    Object Properties Type Annotations

    You can use the type annotation to add the types to the properties of an object.

    Let's define an object using interface as follows −

    interfacePerson{
       name:string;
       age:number;}const person: Person ={
       name:"John Doe",
       age:35,}

    In the above example, we added types string and number to the properties name and age respectively.

    You can assign only string value to the name property and similarly only number value to the age property. Suppose if you try to add a string to age, it will throw an error.

    Type 'string' is not assignable to type 'number'.

    Example

    Let's take a complete example. In this example, we define an interface named Person with two properties name and age. The name property is annotated as string and age is as number. We create an object named person using the interface Person. Then finally, we display the object properties in the console.

    Open Compiler

    interfacePerson{
       name:string;
       age:number;}const person: Person ={
       name:"John Doe",
       age:35,}console.log(The person's name is ${person.name} and person's age is ${person.age});

    On compiling, it will produce the following JavaScript code −

    const person ={
    
    name:"John Doe",
    age:35,};
    console.log(The person's name is ${person.name} and person's age is ${person.age});

    The output of the above example code if as follows −

    The person's name is John Doe and person's age is 35
    

    The type annotations of variables, function parameters and return types, etc. are recommended in TypeScript. But also TypeScript supports dynamic typing as in JavaScript. As you already know that TypeScript supports all ECMAScript features.

  • Types

    The Type System represents the different types of values supported by the language. The Type System checks the validity of the supplied values, before they are stored or manipulated by the program. This ensures that the code behaves as expected. The Type System further allows for richer code hinting and automated documentation too.

    TypeScript provides data types as a part of its optional Type System. The data type classification is as given below −

    Data Types

    The Any type

    The any data type is the super type of all types in TypeScript. It denotes a dynamic type. Using the any type is equivalent to opting out of type checking for a variable.

    Built-in types

    The following table illustrates all the built-in types in TypeScript −

    Data typeKeywordDescription
    NumbernumberDouble precision 64-bit floating point values. It can be used to represent both, integers and fractions.
    StringstringRepresents a sequence of Unicode characters
    BooleanbooleanRepresents logical values, true and false
    VoidvoidUsed on function return types to represent non-returning functions
    NullnullRepresents an intentional absence of an object value.
    UndefinedundefinedDenotes value given to all uninitialized variables
    SymbolsymbolA unique and immutable primitive introduced in ES2015.
    ObjectobjectRepresents instances of user-defined classes, arrays, functions, etc.
    NeverneverRepresents values that never occur.

    There is no integer type in TypeScript and JavaScript.

    Now, lets understand each built-in data type in detail.

    Number

    In TypeScript, the number data type can store the integer, floating point, binary, decimal, hexadecimal, etc. numbers. However, all integers are represented as floating points in TypeScript.

    Example

    In the code below, the age and marks both variables are of number type. The age variable contains the integer value and the marks variable contains the floating point value.

    // Integer numberlet age:number=30;// Float numberlet marks:number=30.5;

    String

    The string data type is used to store the text value.

    You can define a string using three ways:

    • Using the single quote
    • Using the double quotes
    • Using the backticks

    The backticks are used to create multiline or template strings.

    Example

    In the code below, the first_name string is created using the single quote, and the last_name string is created using the double quotes. The full_name string is created using the backticks, which uses the template literals to create a string.

    let first_name:string='John';let last_name:string="Doe";let full_name:string=${first_name} ${last_name};

    Boolean

    In TypeScript, Boolean data type allows you to represent logical entities. It stores the either true or false value. The boolean variables are mainly used with conditional statements like if-else or switch to execute a flow based on some logical value.

    Example

    In the code below, the isReady is a variable of boolean type, which contains the true value.

    let isReady:boolean=true;

    Symbol

    The symbol is a primitive data type, which is mostly used to create unique values. It allows developers to create unique object keys that wont collide with any other keys.

    Example

    Here, we have used the Symbol() constructor which returns the new unique key. We have used the UNIQUE_KEY as a key of the obj object.

    // Define a symbolconstUNIQUE_KEY=Symbol();// Use the symbol as a property key in an objectlet obj ={[UNIQUE_KEY]:"SecretValue"};

    Null

    The null type in TypeScript represents the intentional absence of any object value. It is one of the primitive types and is typically used to indicate that a variable intentionally points to no object.

    Example

    In the code below, the empty variable contains the null value.

    let empty:null=null;

    Undefined

    The undefined data type represents the absence of value. When a variable is declared but is not initialized, it contains the undefined value.

    Example

    In the code below, the undef variable contains the undefined value.

    let undef:undefined;

    Null and undefined Are they the same?

    The null and the undefined datatypes are often a source of confusion. The null and undefined cannot be used to reference the data type of a variable. They can only be assigned as values to a variable.

    However, null and undefined are not the same. A variable initialized with undefined means that the variable has no value or object assigned to it while null means that the variable has been set to an object whose value is undefined.

    Object

    The object is a non-primitive data type, which can contain any value that is not a number, string, boolean, symbol, null, or undefined. You can create an object using either object literal or Object() constructor.

    Example

    In the code below, we have created the object using the object literal. The type of the person variable is an object. We have added the key-value pair between the curly braces (object literal).

    let person: object ={name:"Bob"};

    Void

    The void type is used in the return type of functions that do not return a value. It signifies that there is no type at all.

    Example

    Here, we have used the void data type with function to not return any value from the function.

    functionlog():void{console.log("log");}

    User-defined Types

    User-defined types include Enumerations (enums), classes, interfaces, arrays, and tuple. These are discussed in detail in the later chapters.

    Array

    The array data type is a collection of the same elements. It stores the elements, which you can access or update using the array index that starts from 0.

    The array of any data type can be defined as data_type[] or Array<data_type>, where <data_type> can be any primitive or non-primitive data type.

    Example

    In the code below, we have defined the array of numbers which contains only 3 elements. The index of 1 is 0, the index of 2 is 1, and the index of 3 is 2.

    let numbers:number[]=[1,2,3];

    Tuple

    Tuple types allow you to express an array with a fixed number of elements whose types are known, but need not be the same. This adds a level of safety when dealing with arrays that need to have a specific structure.

    Example

    In the code below, the tuple variable can have an array of length 2 as a value. The first element of the tuple is of string type, and the second element of the tuple is of number type.

    let tuple:[string,number]=["hello",10];console.log(tuple);// Output: ["hello", 10]

    Enum

    An enumeration is a collection of related values that can be numeric or string values. enum makes it easy to handle sets of related constants in a more readable way.

    Example

    In the code below, the Color enum contains the different colors. We can access the color using the enum name which is Color followed by a dot and color name value.

    enum Color {Red, Green, Blue}let c: Color = Color.Green;console.log(c);// Output: 1

    Print Page

  • let & const

    TypeScript has the same rules as JavaScript to declare variables. Initially, only the ‘var’ keyword was used to declare the variable, but in the ES6 version of JavaScript ‘let’ and ‘const’ keywords are introduced to declare a variable. So, you can also use them in TypeScript.

    In this lesson, you will learn to declare a variable using the ‘let’ and ‘const’ keywords and how those variables are different from the variables declared using the ‘var’ keyword.

    Declaring a variable using the let keyword

    When we declare the variable using the ‘let’ keyword in TypeScript, the scoping rule and hoisting rule remain the same as in JavaScript.

    Syntax

    The syntax to declare a variable using the ‘let’ keyword in TypeScript is as follows

    let var_name: var_type = value;
    • In the above syntax, ‘let’ is a keyword.
    • ‘var_name’ is a valid identifier for a variable name.
    • ‘var_type’ is a type of the variable.
    • ‘value’ is a value to store in the variable.

    Example

    In the code below, we have defined the ‘car_name’ variable of string type which contains the Brezza value. The ‘car_price’ variable contains the 1000000 number value.

    Open Compiler

    // Define a variable in TypeScriptlet car_name:string="Brezza";let car_price:number=1000000;console.log(car_name);console.log(car_price);

    On compiling, it will generate the following JavaScript code.

    // Define a variable in TypeScriptlet car_name ="Brezza";let car_price =1000000;
    console.log(car_name);
    console.log(car_price);

    Output

    The output of the above example code is as follows

    Brezza
    1000000
    

    Variable Scope

    The variables declared using the ‘let’ keyword have the block scope. It means you can’t access the variable outside the block unlike the variable declared using the ‘var’ keyword.

    Let’s learn it via the example below.

    In the code below, the ‘bool’ variable contains a true value so the code of the ‘if’ statement will always execute. In the ‘if’ block, we have declared the ‘result’ variable which can be accessed inside the ‘if’ block only. If you try to access it outside the ‘if’ block, the TypeScript compiler will throw an error.

    Open Compiler

    let bool:boolean=true;if(bool){let result:number=10;console.log(result);// It can have accessed only in this block}// console.log(result); Can't access variable outside of the block.

    Let variables cannot be re-declared

    You can’t re-declare the variables that are declared using the ‘let’ keyword.

    Let’s look at the example below.

    In the code below, you can observe that if we try to re-declare the same variable, the TypeScript compiler throws an error.

    Open Compiler

    let animal:string="cat";// let animal: string = "dog"; // Error: Cannot redeclare block-scoped variable 'animal'console.log(animal);// Output: cat

    On compiling, it will generate the following JavaScript code.

    let animal ="cat";// let animal: string = "dog"; // Error: Cannot redeclare block-scoped variable 'animal'
    console.log(animal);// Output: cat

    The output of the above example code is as follows

    cat
    

    Variables with the same name in different blocks

    The variables declared using the ‘let’ keyword have a block scope. So, variables with the same name but if they are in different blocks, are considered as different variables.

    Let’s look at the examples below.

    In the code below, we have declared the ‘num’ variable in ‘if’ and ‘else’ both blocks and initialized them with different values.

    Open Compiler

    let bool:boolean=false;// If the boolean is true, the variable num will be 1, otherwise it will be 2if(bool){let num:number=1;console.log(num);}else{let num:number=2;console.log(num);}

    On compiling, it will generrate the following JavaScript code.

    let bool =false;// If the boolean is true, the variable num will be 1, otherwise it will be 2if(bool){let num =1;
    
    console.log(num);}else{let num =2;
    console.log(num);}</code></pre>

    The output of the above example code is as follows

    2
    

    Declaring a variable using a 'const' keyword

    The 'const' keyword has the same syntax as 'var' and 'let' to declare variables. It is used to declare the constant variables. Furthermore, you need to initialize the 'const' variables while defining them, and you can't change them later.

    Syntax

    The syntax to declare a variable using the 'const' keyword in TypeScript is as follows

    const var_name: var_type = value;

    In the above syntax, 'const' is a keyword.

    Example

    In the code below, we have defined the 'lang' and 'PI' variables using the 'const' keywords, which contain the 'TypeScript' and '3.14' values, respectively.

    Open Compiler

    // Define a constant variable in TypeScriptconst lang:string='TypeScript';constPI:number=3.14;console.log(Language: ${lang});console.log(Value of PI: ${PI});

    On compiling, it will generate the following JavaScript code.

    // Define a constant variable in TypeScriptconst lang ='TypeScript';constPI=3.14;
    console.log(Language: ${lang});
    console.log(Value of PI: ${PI});

    The output of the above example code is as follows

    Language: TypeScript
    Value of PI: 3.14
    

    The variables are declared using the 'const' keyword has the same rule for scoping and re-declaration as the variable declared using the 'let' keyword.

    In the code below, you can observe that if you try to re-declare the 'const' variable in the same scope or try to change its value after declaring it, it throws an error.

    Open Compiler

    if(true){constPI:number=3.14;console.log(PI);// const PI: number = 3.14; Error: Cannot redeclare block-scoped variable 'PI'.// PI = 3.15; Error: Cannot assign to 'PI' because it is a constant.}

    On compiling, it will generate the following JavaScript code.

    if(true){constPI=3.14;
    
    console.log(PI);// const PI: number = 3.14; Error: Cannot redeclare block-scoped variable 'PI'.// PI = 3.15; Error: Cannot assign to 'PI' because it is a constant.}</code></pre>

    The output of the above example code is as follows

    3.14 
    

    You learned to use the 'let' and 'const' statements to declare variables. It is always a good idea to declare a variable using the 'let' keyword due to its block scoping features, which avoids the overriding of values of variables declared in the different scopes.

  • Variables

    A variable, by definition, is a named space in the memory that stores values. In other words, it acts as a container for values in a program. TypeScript variables must follow the JavaScript naming rules −

    • Variable names can contain alphabets and numeric digits.
    • They cannot contain spaces and special characters, except the underscore (_) and the dollar (&dollar;) sign.
    • Variable names cannot begin with a digit.

    A variable must be declared before it is used. Use the var keyword to declare variables.

    Variable Declaration in TypeScript

    The type syntax for declaring a variable in TypeScript is to include a colon (:) after the variable name, followed by its type. Just as in JavaScript, we use the var keyword to declare a variable.

    When you declare a variable, you have four options −

    • Declare its type and value in one statement.
    Declare Type
    • Declare its type but no value. In this case, the variable will be set to undefined.
    Undefined
    • Declare its value but no type. The variable type will be set to the data type of the assigned value.
    Any
    • Declare neither value not type. In this case, the data type of the variable will be any and will be initialized to undefined.
    Any and Undefined

    The following table illustrates the valid syntax for variable declaration as discussed above −

    S.No.Variable Declaration Syntax & Description
    1.var name:string = maryThe variable stores a value of type string
    2.var name:string;The variable is a string variable. The variables value is set to undefined by default
    3.var name = maryThe variables type is inferred from the data type of the value. Here, the variable is of the type string
    4.var name;The variables data type is any. Its value is set to undefined by default.

    Example: Variables in TypeScript

    Open Compiler

    var name:string="John";var score1:number=50;var score2:number=42.50var sum = score1 + score2 
    console.log("name"+name)console.log("first score: "+score1)console.log("second score: "+score2)console.log("sum of the scores: "+sum)

    On compiling, it will generate following JavaScript code.

    //Generated by typescript 1.8.10var name ="John";var score1 =50;var score2 =42.50;var sum = score1 + score2;console.log("name"+ name);console.log("first score: "+ score1);console.log("second score : "+ score2);console.log("sum of the scores: "+ sum);

    The output of the above program is given below −

    name:John 
    first score:50 
    second score:42.50 
    sum of the scores:92.50
    

    The TypeScript compiler will generate errors, if we attempt to assign a value to a variable that is not of the same type. Hence, TypeScript follows Strong Typing. The Strong typing syntax ensures that the types specified on either side of the assignment operator (=) are the same. This is why the following code will result in a compilation error −

    var num:number="hello"// will result in a compilation error

    Type Assertion in TypeScript

    TypeScript allows changing a variable from one type to another. TypeScript refers to this process as Type Assertion. The syntax is to put the target type between < > symbols and place it in front of the variable or expression. The following example explains this concept −

    Example

    Open Compiler

    var str ='1'var str2:number=<number><any> str   //str is now of type number console.log(typeof(str2))

    If you hover the mouse pointer over the type assertion statement in Visual Studio Code, it displays the change in the variables data type. Basically it allows the assertion from type S to T succeed if either S is a subtype of T or T is a subtype of S.

    The reason why it’s not called “type casting” is that casting generally implies some sort of runtime support while, type assertions are purely a compile time construct and a way for you to provide hints to the compiler on how you want your code to be analyzed.

    On compiling, it will generate following JavaScript code.

    "use strict";var str ='1';var str2 = str;//str is now of type number console.log(typeof(str2));

    It will produce the following output −

    string
    

    Inferred Typing in TypeScript

    Given the fact that, Typescript is strongly typed, this feature is optional. TypeScript also encourages dynamic typing of variables. This means that, TypeScript encourages declaring a variable without a type. In such cases, the compiler will determine the type of the variable on the basis of the value assigned to it. TypeScript will find the first usage of the variable within the code, determine the type to which it has been initially set and then assume the same type for this variable in the rest of your code block.

    The same is explained in the following code snippet −

    Example: Inferred Typing

    var num =2;// data type inferred as  number console.log("value of num "+num); 
    num ="12";console.log(num);

    In the above code snippet −

    • The code declares a variable and sets its value to 2. Note that the variable declaration doesnt specify the data type. Hence, the program uses inferred typing to determine the data type of the variable, i.e., it assigns the type of the first value that the variable is set to. In this case, num is set to the type number.
    • When the code tries to set the variables value to string. The compiler throws an error as the variables type is already set to number.

    It will produce the following output −

    error TS2011: Cannot convert 'string' to 'number'.
    

    TypeScript Variable Scope

    The scope of a variable specifies where the variable is defined. The availability of a variable within a program is determined by its scope. TypeScript variables can be of the following scopes −

    • Global Scope − Global variables are declared outside the programming constructs. These variables can be accessed from anywhere within your code.
    • Class Scope − These variables are also called fields. Fields or class variables are declared within the class but outside the methods. These variables can be accessed using the object of the class. Fields can also be static. Static fields can be accessed using the class name.
    • Local Scope − Local variables, as the name suggests, are declared within the constructs like methods, loops etc. Local variables are accessible only within the construct where they are declared.

    The following example illustrates variable scopes in TypeScript.

    Example: Variable Scope

    Open Compiler

    var global_num =12//global variable classNumbers{ 
       num_val =13;//class variable static sval =10;//static field storeNum():void{var local_num =14;//local variable }}console.log("Global num: "+global_num)console.log(Numbers.sval)//static variable  var obj =newNumbers();console.log("Global num: "+obj.num_val)

    On transpiling, the following JavaScript code is generated −

    var global_num =12;//global variable var Numbers =(function(){functionNumbers(){this.num_val =13;//class variable }
       Numbers.prototype.storeNum=function(){var local_num =14;//local variable };
       Numbers.sval =10;//static field return Numbers;}());console.log("Global num: "+ global_num);console.log(Numbers.sval);//static variable  var obj =newNumbers();console.log("Global num: "+ obj.num_val);

    It will produce the following output −

    Global num: 12
    10
    Global num: 13
    

    If you try accessing the local variable outside the method, it results in a compilation error.

    error TS2095: Could not find symbol 'local_num'.