Author: saqibkhan

  • Loops

    You may encounter situations, when a block of code needs to be executed several number of times. In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.

    Programming languages provide various control structures that allow for more complicated execution paths.

    A loop statement allows us to execute a statement or group of statements multiple times. Given below is the general form of a loop statement in most of the programming languages.

    Loop

    TypeScript provides different types of loops to handle looping requirements. The following figure illustrates the classification of loops −

    Loop Types

    Definite Loop

    A loop whose number of iterations are definite/fixed is termed as a definite loop. The for loop is an implementation of a definite loop.

    S.No.Loops & Description
    1.for loopThe for loop is an implementation of a definite loop.

    Indefinite Loop

    An indefinite loop is used when the number of iterations in a loop is indeterminate or unknown.

    Indefinite loops can be implemented using −

    S.NoLoops & Description
    1.while loopThe while loop executes the instructions each time the condition specified evaluates to true.
    2.do whileThe dowhile loop is similar to the while loop except that the do…while loop doesnt evaluate the condition for the first time the loop executes.

    Example: while versus do..while

    var n:number=5while(n >5){console.log("Entered while")}do{console.log("Entered dowhile")}while(n>5)

    The example initially declares a while loop. The loop is entered only if the expression passed to while evaluates to true. In this example, the value of n is not greater than zero, hence the expression returns false and the loop is skipped.

    On the other hand, the dowhile loop executes statement once. This is because the initial iteration does not consider the Boolean expression. However, for the subsequent iteration, the while checks the condition and takes the control out of the loop.

    On compiling, it will generate following JavaScript code −

    var n =5;while(n >5){console.log("Entered while");}do{console.log("Entered dowhile");}while(n >5);

    The above code will produce the following output −

    Entered dowhile
    

    The break Statement

    The break statement is used to take the control out of a construct. Using break in a loop causes the program to exit the loop. Its syntax is as follows −

    Syntax

    break
    

    Flow diagram

    Break Statement

    Example

    Now, take a look at the following example code −

    var i:number=1while(i<=10){if(i %5==0){console.log("The first multiple of 5  between 1 and 10 is : "+i)break//exit the loop if the first multiple is found } 
       i++}//outputs 5 and exits the loop

    On compiling, it will generate the following JavaScript code −

    var i =1;while(i <=10){if(i %5==0){console.log("The first multiple of 5  between 1 and 10 is : "+ i);break;//exit the loop if the first multiple is found}
       i++;}//outputs 5 and exits the loop

    It will produce the following output −

    The first multiple of 5  between 1 and 10 is : 5
    

    The continue Statement

    The continue statement skips the subsequent statements in the current iteration and takes the control back to the beginning of the loop. Unlike the break statement, the continue doesnt exit the loop. It terminates the current iteration and starts the subsequent iteration.

    Syntax

    continue
    

    Flowchart

    Continue Statement

    Example

    An example of the continue statement is given below −

    var num:number=0var count:number=0;for(num=0;num<=20;num++){if(num %2==0){continue}
       count++}console.log(" The count of odd values between 0 and 20 is: "+count)//outputs 10 

    The above example displays the number of odd values between 0 and 20. The loop exits the current iteration if the number is even. This is achieved using the continue statement.

    On compiling, it will generate following JavaScript code.

    var num =0;var count =0;for(num =0; num <=20; num++){if(num %2==0){continue;}
       count++;}console.log(" The count of odd values between 0 and 20 is: "+ count);//outputs 10

    Output

    The count of odd values between 0 and 20 is: 10
    

    The Infinite Loop

    An infinite loop is a loop that runs endlessly. The for loop and the while loop can be used to make an endless loop.

    Syntax: Infinite Loop using for loop

    for(;;) { 
       //statements 
    }
    

    Example: Infinite loop using for loop

    for(;;){console.log(This is an endless loop)}

    Syntax: Infinite loop using while loop

    while(true) { 
       //statements 
    } 
    

    Example: Infinite loop using while loop

    while(true){console.log(This is an endless loop)}

  • Switchcase Statement

    In TypeScript, the switch statement evaluates an expression, matches the expressions value to a case clause, and executes statements associated with that case.

    You can use multiple if…else statements to achieve the similar functionality. However, it is not the best way especially when the all branches depend on a single value.

    Syntax

    The syntax of switch case in TypeScript is as follows −

    switch(variable_expression){case constant_expr1:{//statements; break;}case constant_expr2:{//statements; break;}default:{//statements; break;}}

    The value of the variable_expression is tested against all cases in the switch. If the variable matches one of the cases, the corresponding code block is executed. If no case expression matches the matches the value of the variable_expression, the code within the default block is associated.

    The following rules apply to a switch statement −

    • There can be any number of case statements within a switch.
    • The case statements can include only constants. It cannot be a variable or an expression.
    • The data type of the variable_expression and the constant expression must match.
    • Unless you put a break after each block of code, execution flows into the next block.
    • The case expression must be unique.
    • The default block is optional.

    Flowchart

    The following flow chart explains how a switch-case statement works.

    Switch Case Statement

    Example: switchcase

    var grade:string="A";switch(grade){case"A":{console.log("Excellent");break;}case"B":{console.log("Good");break;}case"C":{console.log("Fair");break;}case"D":{console.log("Poor");break;}default:{console.log("Invalid choice");break;}}

    The example verifies the value of the variable grade against the set of constants (A, B, C, D, and E) and executes the corresponding blocks. If the value in the variable doesnt match any of the constants mentioned above, the default block will be executed.

    On compiling, it will generate the following JavaScript code −

    var grade ="A";switch(grade){case"A":{console.log("Excellent");break;}case"B":{console.log("Good");break;}case"C":{console.log("Fair");break;}case"D":{console.log("Poor");break;}default:{console.log("Invalid choice");break;}}

    The above code will produce the following output −

    Excellent
    

    Example: Without break statement

    When you dont use the break statement with any case in switch statement, the continue executing the next case without terminating it.

    In the example below, we haven’t used the break statement with any case. It executes all the cases and print the respective values.

    var grade:string='A';console.log("Entering switch block");switch(grade){case"A":{console.log("Excellent");}case"B":{console.log("Good");}case"C":{console.log("Fair");}case"D":{console.log("Poor");}default:{console.log("Invalid choice");}}console.log("Exiting switch block");

    On compiling, it will generate the following JavaScript code.

    var grade ='A';console.log("Entering switch block");switch(grade){case"A":{console.log("Excellent");}case"B":{console.log("Good");}case"C":{console.log("Fair");}case"D":{console.log("Poor");}default:{console.log("Invalid choice");}}console.log("Exiting switch block");

    The output of the above example code is as follows

    Entering switch block
    Excellent
    Good
    Fair
    Poor 
    Invalid choice
    Exiting switch block
    
  • Nested if statements

    A nested if statement in TypeScript is an if statement that is present inside the body of another if or else statement. The else…if ladder is a type of nested if statement. The nested if statement or else…if ladder is useful to test multiple conditions. Its syntax is given below −

    Syntax

    if(boolean_expression1){//statements if the expression1 evaluates to true }elseif(boolean_expression2){//statements if the expression2 evaluates to true }elseif(boolean_expression3){//statements if the expression3 evaluates to false }else{//statements if all three boolean expressions result to false}

    When using if…else…if and else statements, there are a few points to keep in mind.

    • An if can have zero or one else’s and it must come after any else…if‘s.
    • An if can have zero to many else…if‘s and they must come before the else.
    • Once an else…if succeeds, none of the remaining else…if‘s or else‘s will be tested.

    Example: elseif ladder

    var num:number=2if(num >0){console.log(num&plus;" is positive")}elseif(num <0){console.log(num+" is negative")}else{console.log(num+" is neither positive nor negative")}

    The snippet displays whether the value is positive, negative or zero.

    On compiling, it will generate the following JavaScript code −

    //Generated by typescript 1.8.10var num =2;if(num >0){console.log(num +" is positive");}elseif(num <0){console.log(num +" is negative");}else{console.log(num +" is neither positive nor negative");}

    Here is the output of the above code −

    2 is positive
    
  • Ifelse Statement

    In TypeScript, the if…else statement controls the program’s execution flow based on the different conditions. If the condition evaluates to true, the if block of code is executed.

    An if can be followed by an optional else block. The else block will execute if the Boolean expression tested by the if statement evaluates to false.

    Syntax

    The simple if…else statement in TypeScript is as follows

    if(boolean_expression){// statement(s) will execute if the boolean expression is true}else{// statement(s) will execute if the boolean expression is false  }

    Flowchart

    The following flow chart shows how the if…else statement works.

    if else Statement

    The if block guards the conditional expression. The block associated with the if statement is executed if the Boolean expression evaluates to true.

    The if block may be followed by an optional else statement. The instruction block associated with the else block is executed if the expression evaluates to false.

    Examples

    Let’s understand the if…else statement in details with the help of some examples in TypeScript.

    Example: Simple if…else

    In the example below, the variable num is assigned the value 12. The condition (num % 2 == 0) checks if num is even. Since 12 divided by 2 has no remainder, the condition evaluates to true, and the block code following the if statement executes.

    var num:number=12;if(num %2==0){console.log("Even");}else{console.log("Odd");}

    On compiling, it will generate the following JavaScript code

    var num =12;if(num %2==0){console.log("Even");}else{console.log("Odd");}

    The above example prints whether the value in a variable is even or odd. The if block checks the divisibility of the value by 2 to determine the same. Here is the output of the above code

    Even 
    

    Example: Condition evaluates false

    In the above example, if you assign the value 13 to the variable num, the condition becomes false because 13 divided by 2 leaves a remainder of 1. So the block code following the else statement executes.

    var num:number=13;if(num %2==0){console.log("Even");}else{console.log("Odd");}

    On compiling, it will generate the following JavaScript code.

    var num =13;if(num %2==0){console.log("Even");}else{console.log("Odd");}

    Here the condition (13 % 2 == 0) evaluates to false and the else block executes. The output is as follows

    Odd
    

    Example: else if statement

    let grade:number=85;if(grade >=90){console.log("Excellent");}elseif(grade >=80){console.log("Great");}else{console.log("Keep studying");}

    Here, the if statement first checks for the condition, grade >=90. If the condition evaluates to false, the else if statement checks for the condition, grade >= 80. Finally, else block executes only if conditions are false.

    On compiling, it will generate the following JavaScript code.

    let grade =82;if(grade >=90){console.log("Excellent");}elseif(grade >=80){console.log("Great");}else{console.log("Keep studying");}

    Here, the condition of the else if statement evaluates to true, so it prints Great as output.

    Great
    
  • If Statement

    In TypeScript, the if statement evaluates a condition (a boolean expression) and executes a block of code only if the condition is true. The condition is evaluated before the block of code block is executed.

    If the condition is false, the code block following the else (if present) is executed. We will discuss the if…else statement in more detail in the next chapter.

    Syntax

    To write an if statement syntax, we use the if keyword followed by a condition in parentheses and then a block of code enclosed in curly braces ({}).

    if(boolean_expression){// statement(s) will execute if the boolean expression is true  }

    If the Boolean expression evaluates to true, then the block of code inside the if statement will be executed. If the Boolean expression evaluates to false, then the first set of code after the end of the if statement (after the closing curly brace) will be executed.

    Flowchart

    The following flow chart shows how the if statement works.

    If Statement

    Examples

    Let’s understand the if statement in details with the help of some examples in TypeScript.

    Example 1

    In the example below, we define a variable num of number type and assign it the value 5. Since the condition evaluates to true and the code of the if statement is executed.

    var  num:number=5if(num >0){console.log("number is positive")}

    On compiling, it will generate following JavaScript code.

    var num =5;if(num >0){console.log("number is positive");}

    The above example will print “number is positive” as the condition specified by the if block is true.

    number is positive
    

    Example 2

    In the example below, the condition is a boolean variable isQualified. If isQualified is true, the if statement executes the block of code following it.

    var isQualified:boolean=true;if( isQualified ){console.log("Qualified for driving");}

    On compiling, it will generate the following JavaScript code.

    var isQualified =true;if( isQualified ){console.log("Qualified for driving");}

    The above example will print “Qualified for driving” as the condition specified by the if block is true.

    Qualified for driving
    

    Example 3

    In the example below, we define variables x, and y of number type and assign values 20 & 30 to them. The condition of the if statement is x < y. With these given values, the condition evaluates to true, so the code within the if statement is executed.

    var x:number=20;var y:number=30;if(x < y){console.log("x is less than y");}

    On compiling, it will produce the following JavaScript code.

    var x =20;var y =30;if(x < y){console.log("x is less than y");}

    The above example will print “x is less than y” as the condition (20 < 30) specified by the if statement is true.

    x is less than y
    

    Example 4: When condition is false

    var x:number=100;var count:number=0;if(x <100){
    
    count++;}console.log(count);</code></pre>

    On compiling, it will produce the following JavaScript code.

    var x =100;var count =0;if(x <100){
    
    count++;}console.log(count);</code></pre>

    Since the condition (x < 100) evaluates to false, the if block will not be executed. The value of count will remain same as previous. The output is as follows

    0
    
  • Decision Making

    In TypeScript, the decision making statements are used to control the flow of the execution based on certain conditions. TypeScript support all types of decision making constructs available in ES6, including if, if else, switch statements. As a superset of JavaScript, TypeScript inherits and expands upon JavaScripts features including decision-making statements.

    Decision-making structures require that the programmer specifies one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.

    Shown below is the general form of a typical decision-making structure found in most of the programming languages −

    Decision Making

    A decision-making construct evaluates a condition before the instructions are executed. Decision-making constructs in TypeScript are classified as follows −

    S.No.Statement & Description
    1.if statementAn if statement consists of a Boolean expression followed by one or more statements.
    2.if…else statementAn if statement can be followed by an optional else statement, which executes when the Boolean expression is false.
    3.elseif and nested if statementsYou can use one if or else if statement inside another if or else if statement(s).
    4.switch statementA switch statement allows a variable to be tested against a list of values.

    Examples

    Let’s understand the decision making in detail with the help of some examples in TypeScript.

    Example: If Statement

    In the example below, the if statement checks the condition “age >= 18”. The condition (boolean expression) is true so the statement within curly brackets ({}) is executed.

    let age:number=19;if(age >=18){console.log("You care eligible for voting.");}

    On compiling it will generate the following JavaScript code.

    let age =19;if(age >=18){
    
    console.log("You care eligible for voting.");}</code></pre>

    The output of the above example code is as follows

    You are eligible for voting.
    

    So what if the condition (boolean expression) age >= 18 is evaluated as false.

    If the condition is false, else statement will be executed.

    Lets check the flowing example

    Example: Ifelse statement

    In this example, the condition (age >= 18) is evaluated to false so the statement following the else statement is executed.

    let age:number=17;if(age >=18){console.log("You care eligible for voting.");}else{console.log("You are not eligible for voting.")}

    On compiling, it will generate the following JavaScript code.

    let age =17;if(age >=18){
    
    console.log("You care eligible for voting.");}else{
    console.log("You are not eligible for voting.")}</code></pre>

    The output of the above example code is as follows

    You are not eligible for voting.
    

    Example: Nested if statements

    In the example below, else...if ladder used to check multiple conditions. The condition grade >= 80 evaluates to true so it will print "You got a B grade" in the console.

    var grade:number=85;if(grade >=90){console.log("You got an A grade");}elseif(grade >=80){console.log("You got a B grade ");}elseif(grade >=70){console.log("You got a C grade ");}elseif(grade >=60){console.log("You got a D grade ");}else{console.log("You got an F grade ");}

    On compiling, it will generate the following JavaScript code.

    var grade =85;if(grade >=90){
      console.log("You got an A grade");}elseif(grade >=80){
      console.log("You got a B grade ");}elseif(grade >=70){
      console.log("You got a C grade ");}elseif(grade >=60){
      console.log("You got a D grade ");}else{
      console.log("You got an F grade ");}

    The output of the above example code is as follows

    You got a B grade
    

    Example: Switch statement

    The example below, we use the grade variable as an expression of switch case statement. It verifies the value of grade against the case constants (A, B and C) and executes the corresponding block. If value of grade does not match with any case value, the default case will be executed.

    var grade:string='B';switch(grade){case'A':{console.log("Excellent");break;}case'B':{console.log("Good");break;}case'C':{console.log("Fair");break;}default:console.log("Unknown grade");}

    On compiling, it will generate the following JavaScript code.

    var grade ='B';switch(grade){case'A':{
    
        console.log("Excellent");break;}case'B':{
        console.log("Good");break;}case'C':{
        console.log("Fair");break;}default: console.log("Unknown grade");}</code></pre>

    The output of the above example code is as follows

    Good
    
  • Type Aliases

    In TypeScript, type aliases is a way to define a type. It allows you to give a specific name to the type or define a custom type using the ‘type’ keyword. Basically, you can make some changes to the primitive and non-primitive data types and can define the custom data types using the type aliases.

    Syntax

    You can follow the syntax below to define type aliases in TypeScript.

    typealiasName= Type;

    In the above code, ‘type’ is a keyword. The ‘AliasName’ is a name of the type aliases. The ‘Type’ can be a primitive, non-primitive, or any custom data type.

    Aliasing Primitive Types

    The basic usage of the type alias of the aliasing the primitive types, meaning creating the copy of the primitive type. For example, in real-time applications, rather than using the string or number data type directly for the userID variable, we can create the userID alias and store the type in that to improve the code maintainability.

    Example

    In the code below, we have defined the ‘UserID’ type alias of number type. The ‘user1’ can variable contain only number value as its type is ‘UserID’.

    // Defining the type aliastypeUserID=number;// Defining the variable of type aliaslet user1: UserID =101;console.log(user1);

    On compiling, it will generate the following JavaScript code.

    // Defining the variable of type aliaslet user1 =101;
    console.log(user1);

    The output is as follows

    101
    

    Aliasing Union Types

    Whenever you want to define a variable that can contain values of multiple types, you can use union types. For instance, if you are developing a function that accepts multiple types of input (like strings and numbers), using a type alias can make function signatures much cleaner. Otherwise, it can make the code complex if you repeat the union type throughout the code.

    Example

    In the code below, the ‘StringOrNumber’ type alias contains the union of the string and number. The logMessage() function accepts the string or numeric value as a parameter as the parameter type is ‘StringOrNumber’.

    Next, we executed the function after passing the string and number as an argument.

    typeStringOrNumber=string|number;functionlogMessage(message: StringOrNumber):void{console.log(message);}logMessage("Hello");logMessage(123);

    On compiling, it will generate the following JavaScript code.

    functionlogMessage(message){
    
    console.log(message);}logMessage("Hello");logMessage(123);</code></pre>

    The output of the above code is as follows

    Hello
    123
    

    Aliasing Tuples

    The tuple alias is used to define the structure of the fixed-size array, which can contain specific types of values in a particular order.

    Example

    In the code below, we have defined the 'RGBColor' tuple to store the RGB values of the color representation. In this tuple alias, all values are numeric.

    typeRGBColor=[number,number,number];let red: RGBColor =[255,0,0];console.log(Red color: ${red});

    On compiling, it will generate the following JavaScript code.

    let red =[255,0,0];
    console.log(Red color: ${red});

    The output of the above code is as follows

    Red color: 255,0,0
    

    Aliasing Object Types

    The object can have properties in the key-value format. Sometimes, you need to define multiple objects with the same structure, you can use the object type aliases. By creating the alias for the object type, you can reuse it.

    Example

    In the code below, we have defined the 'User' type which contains the id and name properties of the string type.

    The 'user' object contains the string id and name.

    // Defining the type alias for the User objecttypeUser={
    
    id:string;
    name:string;};// Defining the user object using the User type aliaslet user: User ={ id:"101", name:"Alice"};console.log(user);</code></pre>

    On compiling, it will generate the following JavaScript code.

    // Defining the user object using the User type aliaslet user ={ id:"101", name:"Alice"};
    console.log(user);

    The output of the above code is as follows

    { id: '101', name: 'Alice' }
    

    Aliasing Function Types

    Aliasing function types can be particularly useful when dealing with higher-order functions or callbacks, providing a clear contract for what functions are supposed to accept and return.

    Example

    In the code below, the 'GreeterFunction' defines the type of the function. It takes the string value as a parameter and returns the string value.

    The 'greet' variable stores the function expression of type 'GreeterFunction'.

    // Define a function typetypeGreeterFunction=(name:string)=>string;// Define a function that matches the typeconst greet:GreeterFunction= name =>Hello, ${name}!;console.log(greet("TypeScript"));

    On compiling, it will generate the following JavaScript code.

    // Define a function that matches the typeconstgreet=name=>Hello, ${name}!;
    console.log(greet("TypeScript"));

    The output is as follows

    Hello, TypeScript!
    

    Using Type Aliases with Generics

    Generic types are used to create the custom types. It takes the type 'T' as a parameter, and creates a new type based on the type 'T'.

    Example

    In the code below, the 'Container' type accepts the type 'T' as a parameter, and defines the object property value of type 'T'.

    After that, while using the 'Container' type, we pass the data type as an argument. For the 'numberContainer' variable, we have used the 'number' type, and for the 'stringContainer' variable, we have used the 'string' data type.

    // Defining the generic type aliastypeContainer<T>={ value:T};// Using the generic type aliaslet numberContainer: Container<number>={ value:123};let stringContainer: Container<string>={ value:"Hello World"};console.log(numberContainer);// Output: { value: 123 }console.log(stringContainer);// Output: { value: 'Hello World' }

    On compiling, it will generate the following JavaScript code.

    // Using the generic type aliaslet numberContainer ={ value:123};let stringContainer ={ value:"Hello World"};
    console.log(numberContainer);// Output: { value: 123 }
    console.log(stringContainer);// Output: { value: 'Hello World' }

    The output of the above code s as follows

    { value: 123 }
    { value: 'Hello World' }
    

    Type aliases is the way to define custom types, also allowing to reuse of the complex type after defining once. It also helps in improving the code readability and minimizes the code complexity.

  • null vs. undefined

    In TypeScript, ‘undefined’ denotes that a variable has been declared but has not been assigned any value. On the other hand, ‘null’ refers to a non-existent object which is basically ’empty’ or ‘nothing’.

    Have you ever faced a scenario where you need to declare the variable but need to initialize it later? It generally happens while dealing with the APIs where you need to initialize the variables after getting an API response. In such cases, you can use the null or undefined data types to represent the absence of values.

    What is null?

    In TypeScript, ‘null’ is a primitive value, which represents the no value assigned to the variable. It is explicitly assigned to the variable to indicate the variable is empty or doesn’t contain any value.

    Let’s understand how to use the ‘null’ in TypeScript via the examples below.

    Example: Basic use of null

    In the code below, we have defined a variable of ‘null’ type. It represents the variable ‘a’ contains an empty value. In the output, you can observe that it prints a null value.

    // Using null valuelet a:null=null;console.log(a);// null

    On compiling, it will generate the following JavaScript code.

    // Using null valuelet a =null;
    console.log(a);// null

    The ouput of the above code is as follows

    null
    

    Example: Data type of null

    The data type of the ‘null’ type variable is an object.

    Here, we have used the ‘typeof’ operator to check the data type of the variable containing the null value. It returns the object which you can observe in the output.

    let a:null=null;console.log(typeof a);// Object

    On compiling, it will generate the following JavaScript code.

    let a =null;
    console.log(typeof a);// Object

    The output of the above code is as follows

    object
    

    Example: Reinitializing null variable

    In the code below, the data type of the variable ‘a’ is either number or null. Initially, we have assigned a null value to that. After that, we have assigned the number value to the variable ‘a’.

    let a:number|null=null;console.log("The initial value of the variable a is: "+ a);// null
    a =10;console.log("The value of the variable a is: "+ a);// 10

    On compiling, it will generate the following JavaScript code.

    let a =null;
    console.log("The initial value of the variable a is: "+ a);// null
    a =10;
    console.log("The value of the variable a is: "+ a);// 10

    Its output is as follows

    The initial value of the variable a is: null
    The value of the variable a is: 10
    

    What is undefined?

    When you declare the variable but don’t assign any value, TypeScript automatically assigns the ‘undefined’ value to the variable. Whenever you don’t return anything from the function, it returns the undefined value. However, you can also explicitly assign an undefined value to the variable of type ‘undefined’.

    Let’s understand about undefined via the examples below.

    Example: Undefined Values

    In the code below, we have defined the variable ‘a’ but haven’t initialized it with the value. So, its value is undefined which you can see in the output.

    let a:number;console.log("The value of a is "+ a);

    On compiling, it will show the following error

    Variable 'a' is used before being assigned.
    

    And also it will generate the following JavaScript code.

    let a;
    console.log("The value of a is "+ a);

    The output of the above JavaScript code is as follows

    The value of a is undefined
    

    Example: Not returning a value from the function

    In the code below, we have defined the greet() function which doesn’t return any value.

    After that, we invoked the greet() function and stored its outcomes in the variable ‘a’. The value of the variable is undefined as the greet() function doesn’t return any value.

    // Not returning a value from the functionfunctiongreet(name:string):void{console.log(Hello ${name});}let a =greet('John');console.log(a);// undefined

    On compiling, it will generate the following JavaScript code.

    // Not returning a value from the functionfunctiongreet(name){
    
    console.log(Hello ${name});}let a =greet('John');
    console.log(a);// undefined

    The output of the above code is as follows

    Hello John
    Undefined
    

    Example: Using the undefined type

    Here, we have used the ‘undefined’ data type with the variable ‘a’ and assigned an undefined value to it.

    The type of the variable ‘a’ is undefined but not object as like the ‘null’ type variables.

    let a:undefined=undefined;console.log(a);// undefinedconsole.log(typeof a);// undefined

    On compiling, it will generate the following JavaScript code.

    let a =undefined;
    console.log(a);// undefined
    console.log(typeof a);// undefined

    The output is as follows

    undefined
    undefined
    

    Null vs. Undefined: Key Differences

    You learned about Null and Undefined. Now, let’s look at the key differences between them.

    Featurenullundefined
    MeaningExplicitly no valueNot initialized
    Typical UseIntentionally empty or absent valueVariable declared but not yet assigned
    Type AnnotationHas its own type nullHas its own type undefined
    Default BehaviorDoes not trigger default function parametersTriggers default function parameters
    Function ParametersUsed to denote explicitly that parameter should not have a valueIndicates missing parameters or optional parameters
    Object PropertiesCan be used to indicate properties that are deliberately set to no valueUsed for properties that may not be initialized
    Operational HandlingMust be handled explicitly in logic to avoid errorsOften handled with default values or optional chaining

    Let’s look at the examples below which shows where to use null and undefined values.

    Example: Object Properties

    In the code below, the ‘user’ type has ‘name’, ‘age’, and ’email’ properties. The ‘age’ property can accept a null value if the user’s age is not available. The ’email’ property is optional so it’s fine if we don’t use it while defining the object.

    The ‘user1’ object contains the ‘age’ property with the null value. The ‘user2′ value doesn’t contain the ’email’ property. So, it is undefined for the ‘user2’ object.

    typeUser={
    
    name:string;
    age:number|null;
    email?:string;};let user1: User ={
    name:"John Doe",
    age:null,// Explicitly no age provided
    email:"[email protected]"};let user2: User ={
    name:"Jane Doe",
    age:25// email is optional and thus can be undefined};console.log(user1);// Output: { name: "John Doe", age: null, email: "[email protected]" }console.log(user2);// Output: { name: "Jane Doe", age: 25 }</code></pre>

    On compiling, it will generate the following JavaScript code.

    let user1 ={
    
    name:"John Doe",
    age:null,// Explicitly no age provided
    email:"[email protected]"};let user2 ={
    name:"Jane Doe",
    age:25// email is optional and thus can be undefined};
    console.log(user1);// Output: { name: "John Doe", age: null, email: "[email protected]" } console.log(user2);// Output: { name: "Jane Doe", age: 25 }

    The output of the above code is as follows

    { name: 'John Doe', age: null, email: '[email protected]' }
    { name: 'Jane Doe', age: 25 }
    

    This way, you can either use the null or undefined to present the absence of the values in the code.

  • Symbols

    In TypeScript, a symbol is a primitive data type that is unique and immutable. The symbols are introduced in ECMAScript 2015 (also known as ES6).

    As we use the number, string, or boolean to create the variables of different data-type, we can use the symbol type to create the Symbol.

    Using the symbol types has many benefits as it provides more features than other data types. In this tutorial, we will learn about the basics of the Symbol and its different uses of the Symbol.

    Syntax

    Symbols in TypeScript are created using the Symbol() constructor function

    let test_symbol =Symbol();

    You can pass a key as a symbol parameter to identify the Symbol.

    let key_symbol =Symbol("key-for-symbol");

    Symbols are unique and immutable

    In TypeScript, you can create multiple symbols that are unique. Even if you create the symbols with the same keys, they will be unique.

    Let’s create two different symbols with the same key.

    let first_sym =Symbol("sym");let second_sym =Symbol("sym");console.log(first_sym === second_sym);

    The above TypeScript code show that both symbols are unique and not comparable.

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

    The output is as follows

    false
    

    Symbols as keys for object properties

    Symbols can also be used as keys for object properties just like strings.

    In the example below, we have created the symbol and defined the object. We used the obj_symbol as a property of the object. Also, we can access it like the object’s normal property.

    const obj_symbol =Symbol();// creating the objectlet object ={// using the obj_symbol as key of object[obj_symbol]:"obj value",};// accessing the symbol property of the objectconsole.log("The value of the obj_symbol property in the object is "+ object[obj_symbol]);

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

    It will produce the following output

    The value of the obj_symbol property in the object is obj value
    

    Symbol with the switch case statement

    As every symbol is unique, we can use it as a case of the switch-case statement. When we use the symbols with the switch case statement, it ensures that every case is unique. If any case doesnt match with the case passed as a parameter of the switch statement, it goes to the default case.

    switch(symbol){case symbol1:breakcase symbol2:break;}

    In the above syntax, a symbol is passed as a parameter of the switch statement. After that, we used the symbol name followed by the case keyword to create a different case.

    Example

    In the example below, we have created four different symbols. After that, we defined the print_symbol function, which contains the switch case statement to handle the different cases.

    In the switch case statement, we are using the symbol values as a case and executing the code of the particular case.

    // different symbolsconst symbol1 =Symbol();const symbol2 =Symbol();const symbol3 =Symbol();const symbol4 =Symbol();functionprint_symbol(symbol){// creating the switch case statementswitch(symbol){// different casescase symbol1:console.log("The case is symbol 1.");break;case symbol2:console.log("The case is symbol 2.");break;case symbol3:console.log("The case is symbol 3.");debugger;break;case symbol4:console.log("The case is symbol 4.");break;default:console.log("The case is default.");}}// calling the functionprint_symbol(symbol2);print_symbol(symbol4);

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

    It will produce the following output

    The case is symbol 2.
    The case is symbol 4.
    

    Unique Symbols

    In TypeScript, Symbol is a primitive data type. So, we need to use it as a type only, but we can also use it as literals using the unique symbol. The symbol includes the unique symbol, which means the unique symbol is a subtype of the symbol.

    We can use the unique symbol with only const variables and readonly properties. If we want to reference the specific symbol type to another variable, we can use the typeof operator.

    Syntax

    You can follow the syntax below to use the symbol as a literal using the unique symbol.

    const test_symbol: unique symbol=Symbol();let symbol1:typeof test_symbol = test_symbol;classC{staticreadonly symb: unique symbol=Symbol("unique symbol");}

    Example

    In the example below, we have declared the test_symbol of the type symbol and used the unique symbol keyword to use the symbol as a type literal. Also, users can observe how we can use the typeof operator to use the symbol as a type literal of the variables declared with the let and var keywords.

    Also, we have used the unique symbol keyword to define the type of the readonly static classs member.

    // here, we used the unique symbol to define the type of the sym1.const test_symbol: unique symbol=Symbol();// we can't reference the unique symbol to the let type of variable// let sym2: unique symbol = Symbol();// to reference the symbol type to the variables declared with the let keyword, using the typeof operator.let symbol1:typeof test_symbol = test_symbol;console.log("The value of symbol1 is "+typeof test_symbol);// referencing the unique symbol to the static class propertyclassC{staticreadonly symb: unique symbol=Symbol("unique symbol");}

    On compiling, it will generate the following JavaScript code

    // here, we used the unique symbol to define the type of the sym1.var test_symbol =Symbol();// we can't reference the unique symbol to the let type of variable// let sym2: unique symbol = Symbol();// to reference the symbol type to the variables declared with the let keyword, using the typeof operator.var symbol1 = test_symbol;
    console.log("The value of symbol1 is "+typeof test_symbol);// referencing the unique symbol to the static class propertyvarC=/** @class */(function(){functionC(){}C.symb =Symbol("unique symbol");returnC;}());

    The above code will produce the following output

    The value of symbol1 is symbol
    
  • Literal Types

    In TypeScript, literal types are subtypes of the primitive data types. The literal types allow you to specify the exact value the variable can contain.

    There are three types of the literal types in TypeScript.

    • String literal types
    • Numeric literal types
    • Boolean literal types

    Each of them allows you to store the specific value in the variable rather than storing the generalized string, numeric, or boolean value.

    Syntax

    You can follow the syntax below to use the literal types in TypeScript.

    typelit_type= type_1 | type_2 | type_3 |...

    In the above syntax, ‘type’ is a keyword to create a type alias. The ‘lit_type’ is the name of the type. The ‘type_1’, ‘type_2′, and type_3’ are values of type string, Boolean, or number.

    String Literal Types

    The string literal type allows you to define a set of specific values from which a variable or function parameter should contain any value.

    Example

    In the code below, we have created the ‘Direction’ type which contains all 4 directions in string format. The type of the move() function parameter is Direction so it accepts any value from the 4 directions.

    If you try to pass any value other than 4 directions as an argument, it throws an error.

    // Defining a custom-type DirectiontypeDirection="North"|"East"|"South"|"West";// Defining a function move that takes a single argument of type Direction.functionmove(direction: Direction){console.log(Moving in the direction: ${direction});}move("North");move("East");// move("Northeast"); // Error: Argument of type '"Northeast"' is not assignable to parameter of type 'Direction'.

    On compiling, it will generate the following JavaScript code.

    // Defining a function move that takes a single argument of type Direction.functionmove(direction){
    
    console.log(Moving in the direction: ${direction});}move("North");move("East");// move("Northeast"); // Error: Argument of type '"Northeast"' is not assignable to parameter of type 'Direction'.</code></pre>

    The output of the above code is as follows

    Moving in the direction: North
    Moving in the direction: East
    

    Numeric Literal Types

    Numeric literal types are similar to string literals but allow you to specify exact numeric values as allowed types.

    Example

    In the code below, the 'SmallPrimes' type contains the small prime numbers till 11 as a value. The type of the 'prime' variable is 'SmallPrimes'. So, it can contain any value from 2, 3, 5, 7, or 11 only.

    typeSmallPrimes=2|3|5|7|11;let prime: SmallPrimes;
    prime =7;console.log(prime);// 7// prime = 4; // Error: Type '4' is not assignable to type 'SmallPrimes'.

    On compiling, it will generate the following JavaScript code.

    let prime;
    prime =7;
    console.log(prime);// 7// prime = 4; // Error: Type '4' is not assignable to type 'SmallPrimes'.

    The output of the above code is follows

    7
    

    Combined Literal Types

    You can combine different types of literals (string, numeric, boolean) using union types to allow a variable to hold a set of specified values.

    Example

    In the code below, the 'MixedLiterals' type contains the click, 404, and true values.

    The action variable can contain any singl value from the 3 values of the 'MixedLiterals' type.

    // Mixed type literalstypeMixedLiterals="Click"|404|true;let action: MixedLiterals;
    
    action ="Click";// Validconsole.log(action);
    
    action =404;// Validconsole.log(action);
    
    action =true;// Validconsole.log(action);// action = "Other"; // Error: Type '"Other"' is not assignable to type 'MixedLiterals'.

    On compiling, it will generate the following JavaScript code.

    let action;
    action ="Click";// Valid
    console.log(action);
    action =404;// Valid
    console.log(action);
    action =true;// Valid
    console.log(action);// action = "Other"; // Error: Type '"Other"' is not assignable to type 'MixedLiterals'.

    The output of the above code is as follows

    Click
    404
    true
    

    Use Cases for Literal Types

    There are multiple use cases of literal types. However, we will look into some real-time use cases of the literal types.

    • Configuration − It is used to define the particular configuration of variables or function parameters that take only specific values.
    • State Management − Type literals can be used for state management.
    • API Response Handling − It is used to handle the API response based on the API response status.

    Literal types in TypeScript enhance the type safety of your applications by allowing you to specify exactly what values are acceptable. It also helps developers maintain the code complexity and improve the readability.