Category: 01. Tutorial

https://cdn3d.iconscout.com/3d/premium/thumb/video-tutorial-3d-icon-png-download-10844628.png

  • 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.

  • Union

    TypeScript gives programs the ability to combine one or two types. Union types are a powerful way to express a value that can be one of the several types. Two or more data types are combined using the pipe symbol (|) to denote a Union Type. In other words, a union type is written as a sequence of types separated by vertical bars.

    Syntax: Union literal

    We use pipe symbol (|) to combine two or more types to achieve a union type in TypeScript −

    Type1 | Type2 | Type3 
    

    Union Type Variable

    We can define a variable of type union of different types. For example,

    let value:number|string|boolean;

    In the above example, we define a variable named value of union type. We can assign numeric, string or boolean value to the variable.

    Example: Union Type Variable

    In the example below, the variable’s type is union. It means that the variable can contain either a number or a string as its value.

    var val:string|number 
    val =12console.log("numeric value of val: "+val) 
    val ="This is a string"console.log("string value of val: "+val)

    On compiling, it will generate following JavaScript code.

    var val;
    val =12;
    console.log("numeric value of val: "+ val);
    val ="This is a string";
    console.log("string value of val: "+ val);

    Its output of the above example code is as follows

    numeric value of val: 12 
    string value of val: this is a string 
    

    Union Type and Function Parameter

    We can define a function with a parameter of union type. When you can call the function, you can pass the argument of any type of union type. For example,

    functiondisplay(name:string|string[]){// function body;}

    In the above code snippet, function display() has parameter of union type (string or string array). You can call the function passing argument either a string or an array of string.

    Example

    In the example below, we defined a function named disp with a parameter of union type.

    The function disp() can accept argument either of the type string or a string array.

    functiondisp(name:string|string[]){if(typeof name =="string"){console.log(name)}else{var i;for(i =0;i<name.length;i++){console.log(name[i])}}}disp("mark")console.log("Printing names array....")disp(["Mark","Tom","Mary","John"])

    On compiling, it will generate following JavaScript code.

    functiondisp(name){if(typeof name =="string"){
    
      console.log(name);}else{var i;for(i =0; i &lt; name.length; i++){
         console.log(name&#91;i]);}}}disp("mark");
    console.log("Printing names array....");disp(["Mark","Tom","Mary","John"]);

    The output is as follows

    Mark 
    Printing names array. 
    Mark 
    Tom
    Mary
    John 
    

    Union Type and Arrays

    Union types can also be applied to arrays, properties and interfaces. The following illustrates the use of union type with an array.

    Example

    The program declares an array. The array can represent either a numeric collection or a string collection.

    var arr:number[]|string[];var i:number; 
    arr =[1,2,4]console.log("**numeric array**")for(i =0;i<arr.length;i++){console.log(arr[i])}  
    
    arr =["Mumbai","Pune","Delhi"]console.log("**string array**")for(i =0;i<arr.length;i++){console.log(arr[i])}

    On compiling, it will generate following JavaScript code.

    var arr;var i;
    arr =[1,2,4];
    console.log("**numeric array**");for(i =0; i < arr.length; i++){
       console.log(arr[i]);}
    arr =["Mumbai","Pune","Delhi"];
    console.log("**string array**");for(i =0; i < arr.length; i++){
       console.log(arr[i]);}

    Its output is as follows −

    **numeric array** 
    1 
    2 
    4 
    **string array** 
    Mumbai 
    Pune 
    Delhi
    
  • Never

    The never type

    The never type in TypeScript represents the values that can never occur. For example, the return type of a function that throws an error is never.

    functionfuncName():never{// it throws an exception or never returns}

    You cannot assign a value to a variable of never type

    let x:never;
    x =10;// throw error

    The above TypeScript code snippet will throw the following errors

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

    You can use the never type as the return type of a function that never returns or always throws an exception.

    A function that never stops executing

    functioninfiniteLoop():never{for(;;){}}

    Another example of function that never stops executing

    functioninfiniteLoop():never{while(true){}}

    Variables also acquire the type never when narrowed by any type guards that can never be true.

    The never type is used when we have exhausted all possible value and we don’t have anything to assign.

    functioncheck(value:string|number){if(typeof value ==='string'){return"value is string";}else{return"value is number";}// here, not a string or number// "value" can't occur here, so it's type "never"}

    The never type is a subtype of, and assignable to, every type; however, no type is a subtype of, or assignable to, never (except never itself). Even any isnt assignable to never.

    You can annotate a variable with never type, but it is very uncommon

    functionshowError():never{thrownewError("Error message from function with never as return type.");}let x:never=showError();

    In the above Typescript code snippet, variable x is annotated with the never type. The variable x is assigned showError() function that itself has the never as return type.

    void vs. never

    In TypeScript, a variable of void type can store undefined as a value. On the other hand, never can’t store any value.

    let val1:void=undefined;let val2:never=undefined;// error: Type 'undefined' is not assignable to type 'never'.

    We know that if a function in TypeScript does not return any value, it returns undefined. We generally annotate the type of return type of such function with void. Look at the below example,

    functiongreet():void{console.log("Welcome to tutorials Point");}let msg:void=greet();console.log(msg);

    In the above example, we defined a function greet() that doesn’t return any value. When we call the function, the return value is undefined.

    On compiling, it will generate the following JavaScript code.

    functiongreet(){console.log("Welcome to tutorials Point");}let msg =greet();console.log(msg);

    The output of the above code is as follows

    Undefined
    
  • Any Type

    The any type in TypeScript is a specific type that can represent any value. It is generally used when a type of variable is unknown or not yet defined. The any type is useful when converting the JavaScript code to TypeScript.

    Any type is not a type in traditional sense. It is like a placeholder that tells the TypeScript compiler to ignore type checking for the particular variable, function, etc.

    Can represent any value

    A variable declared with any type can hold value of any datatype

    let x:any;
    x ="Hello";
    x =23;
    x =true;

    Here the variable x is declared with any type. This allows us to assign any value, string, number, boolean, etc. to the variable.

    The type of a variable of any type is undefined when you check using typeof operator

    let x:any;console.log(typeof x)// undefined

    On compiling, it will generate the following JavaScript code

    let x;
    console.log(typeof x);// undefined

    The output of the above example code is as follows

    undefined
    

    Example

    Let’s understand the any type with help of the below TypeScript example

    let x:any;console.log(typeof x);
    x ="Hello";console.log(typeof x);
    x =23;console.log(typeof x);
    x =true;console.log(typeof x);

    Here the variable is declared of any type. Then assigned this with values of different types (string, number and boolean).

    On compiling, it will generate the following JavaScript code

    let x;
    console.log(typeof x);
    x ="Hello";
    console.log(typeof x);
    x =23;
    console.log(typeof x);
    x =true;
    console.log(typeof x);

    The output of the above example code is as follows

    undefined 
    string 
    number 
    boolean
    

    Function Parameters of any Type

    You can also define a function with parameter of any type

    functionfunc(para:any){}

    Here the function func can take parameter of any type number, string, boolean, etc.

    Example

    Let’s take an example,

    functiongreet(name:any):string{returnHello Mr. ${name};}console.log(greet('Shahid'));console.log(greet(123));

    The function greet() is defined with a parameter of any type. So it can accept an argument of any type (number, string, etc.).

    We have called the greet() function passing two different values of string and number types. You can notice that it works for both types of the arguments.

    On compiling, the above typescript code will generate the following JavaScript code

    functiongreet(name){returnHello Mr. ${name};}
    console.log(greet('Shahid'));
    console.log(greet(123));

    The output of the above example code is as follows

    Hello Mr. Shahid 
    Hello Mr. 123
    

    Object of any Type

    An object can also be defined of any type. Such object can have the properties of any type. Lets take an example

    const student:any={
       name:"John Doe",
       age:32,
       isEnrolled:true,}

    Here the student object declared with any. It consists of three properties of different types.

    Example

    Try the following example,

    const student:any={
       name:"John Doe",
       age:32,
       isEnrolled:true,}console.log(student.name);console.log(student.age);console.log(student.isEnrolled);

    On compiling, it will generate the following JavaScript code

    const student ={
    
    name:"John Doe",
    age:32,
    isEnrolled:true,};
    console.log(student.name); console.log(student.age); console.log(student.isEnrolled);

    The output of the above example code is as follows

    John Doe
    32 
    true
    

    Why to use any Type?

    One reason to use any type is when you are working with the code that are not type-checked. For example, if you are using preexisting JavaScript code, the any type is useful in converting the JavaScript code to TypeScript. If you are using a third party library that is not written in TypeScript, you may need to use any type for the variable in TypeScript code.

    Another reason to use the any type is when you are not sure what will be the type of a value. For example, a function accepting user input can be defined with any type to handle any type of data from users.

    Any type is discouraged to use in new TypeScript code. It is advised to be careful when using the any type. If you use any type too often, you code will become less type safe.

    Type Assertion

    Use type assertion to narrow down the type of any variable

    let value:any="hello world";let lenStr:number=(value asstring).length;console.log(lenStr);

    In the above code, variable value is defined of any type. Then it is narrowed down to string.

    On compiling, it will generate the following JavaScript code

    let value ="hello world";let lenStr = value.length;
    console.log(lenStr);

    The output of the above code is as follows

    11
    

    Caution

    Any type can lead to error if not used with caution.

    In the below example, we are trying to access the property enrYear that doesn’t exist. This will cause a runtime error because we have defined student object with any. Notice it doesn’t show a compile time error.

    const student:any={
       name:"John Doe",
       age:32,
       isEnrolled:true,}console.log(student.name);console.log(student.age);console.log(student.enrYear);

    On compilation, it will generate the following JavaScript code

    const student ={
    
    name:"John Doe",
    age:32,
    isEnrolled:true,};
    console.log(student.name); console.log(student.age); console.log(student.enrYear);

    The output of the above example code is as follows

    John Doe 
    32 
    undefined
    

    Any vs. unknown

    When a variable is declared with any type and you can access its non-existing property.

    Example: Variable declared with any

    let user:any;
    user.isEnrolled;

    The above TypeScript code will not show any error at compilation. But it will through the following run time error.

    Cannot read properties of undefined (reading 'isEnrolled')
    

    Example: Variable declared with unknown

    let user:unknown;
    user.isEnrolled;

    The above code will show a compile time error as follows

    'user' is of type 'unknown'.
    
  • Enums

    Enums in TypeScript allow you to define a set of named constants. An enum is a way of giving more friendly names to sets of numeric values.

    Each enum member has a value associated with it. The value can be either constant or computed. The member value can be a numeric or string value.

    The Enum type in TypeScript is a user-defined data type. TypeScript has some features that are not the type-level extension of the JavaScript. Enum is one of the such few features along with type guards or union.

    enum enumName {// Enum members}

    The enums in TypeScript can be categorized in the following three types

    • Numeric enums
    • String enums
    • Heterogeneous enums

    Numeric Enums

    In this type of enum, members of an enum are assigned numeric values. Numeric enums possess an auto-increment nature. For instance, if we assign the number 5 to the first constant variable of the enum, then the following constant variables assign with values incremented by one, like 6 to the second member of the enum, 7 to the next, and so on.

    Example 1: Default numeric enums

    By default, enums in TypeScript are numeric. The first member is assigned a value of 0, and subsequent members are incremented by 1.

    enum Weekday {
      Monday,
      Tuesday,
      Wednesday,
      Thursday,
      Friday,}console.log(Weekday.Monday);console.log(Weekday.Tuesday);console.log(Weekday.Wednesday);console.log(Weekday.Thursday);console.log(Weekday.Friday);

    On compiling, it will generate the following JavaScript code

    var Weekday;(function(Weekday){
    
    Weekday&#91;Weekday&#91;"Monday"]=0]="Monday";
    Weekday&#91;Weekday&#91;"Tuesday"]=1]="Tuesday";
    Weekday&#91;Weekday&#91;"Wednesday"]=2]="Wednesday";
    Weekday&#91;Weekday&#91;"Thursday"]=3]="Thursday";
    Weekday&#91;Weekday&#91;"Friday"]=4]="Friday";})(Weekday ||(Weekday ={}));
    console.log(Weekday.Monday); console.log(Weekday.Tuesday); console.log(Weekday.Wednesday); console.log(Weekday.Thursday); console.log(Weekday.Friday);

    The output of the above example code is as follows

    0
    1
    2
    3
    4
    

    Notice that the first member is initialized with 0 and the subsequent members are incremented by the 1.

    Example 2: Initiated numeric enums

    In the below example, we have created an enum type named Color. Inside Color, three const variables are created with names Red, Yellow, and Green. We have initialized the first member and left other members for auto increment.

    enum Color{
      Red =10,
      Yellow,
      Green,}//print const variables valuesconsole.log(Color.Red);console.log(Color.Yellow);console.log(Color.Green);

    On compiling, it will generate the following JavaScript code

    var Color;(function(Color){
    
    Color&#91;Color&#91;"Red"]=10]="Red";
    Color&#91;Color&#91;"Yellow"]=11]="Yellow";
    Color&#91;Color&#91;"Green"]=12]="Green";})(Color ||(Color ={}));//print const variables values
    console.log(Color.Red); console.log(Color.Yellow); console.log(Color.Green);

    The output of the above example code is as follows

    10
    11
    12
    

    Example 3: Fully initialized numeric enums

    We can also set the values of all members of an enum. In the example below, we have initialized all member of the enum HttpStatus.

    enum HttpStatus {
      Success =200,
      NotFound =404,
      InternalServerError =500,}console.log(HttpStatus.Success);console.log(HttpStatus.NotFound);console.log(HttpStatus.InternalServerError);

    On compiling, it will generate the following JavaScript code

    var HttpStatus;(function(HttpStatus){
    
    HttpStatus&#91;HttpStatus&#91;"Success"]=200]="Success";
    HttpStatus&#91;HttpStatus&#91;"NotFound"]=404]="NotFound";
    HttpStatus&#91;HttpStatus&#91;"InternalServerError"]=500]="InternalServerError";})(HttpStatus ||(HttpStatus ={}));
    console.log(HttpStatus.Success); console.log(HttpStatus.NotFound); console.log(HttpStatus.InternalServerError);

    The output of the above example code is as follows

    200
    404
    500
    

    String Enums

    String enums are similar to numeric ones except that values of enums members are assigned with strings instead of numeric ones. The string enums do not possess auto-increment behavior.

    Example

    The following example creates an enum TrafficLight with three members. The members are initialized with string literals.

    enum TrafficLight {
      Red ="stop",
      Yellow ="caution",
      Green ="go",}console.log(TrafficLight.Red);console.log(TrafficLight.Yellow);console.log(TrafficLight.Green);

    On compiling, it will generate the following JavaScript code

    var TrafficLight;(function(TrafficLight){
    
    TrafficLight&#91;"Red"]="stop";
    TrafficLight&#91;"Yellow"]="caution";
    TrafficLight&#91;"Green"]="go";})(TrafficLight ||(TrafficLight ={}));
    console.log(TrafficLight.Red); console.log(TrafficLight.Yellow); console.log(TrafficLight.Green);

    The output of the above example code is as follows

    stop
    caution
    go
    

    Heterogeneous Enums

    This is a combination of both numeric and string enums. That is, in this type of enum, we can assign both string values or numeric values to its members.

    Example

    In the below example, we have created an enum type of Student. Inside the student are three const variables: Name, Gender, and Mobile. Name and Gender are of literal string types, whereas Mobile is of numeric value.

    enum student{
      Name ="srujana",
      Gender ="female",
      Mobile =901234567,}console.log(student.Name);console.log(student.Gender);console.log(student.Mobile);

    On compiling, it will generate the following JavaScript code

    var student;(function(student){
    
    student&#91;"Name"]="Srujana";
    student&#91;"Gender"]="Female";
    student&#91;student&#91;"Mobile"]=901234567]="Mobile";})(student ||(student ={}));
    console.log(student.Name); console.log(student.Gender); console.log(student.Mobile);

    The output of the above example code is as follows

    Srujana
    Female
    901234567
    

    Enums at runtime

    The enums are real objects that exist at run time. In the below example, the enum E is passed as parameter object to a function. It works, since ‘E’ has a property named ‘y’ which is a number.

    enum En {
      x,
      y,
      z,}functionfunc(obj:{ y:number}){return obj.y;}console.log(func(En));console.log(typeof En);

    On compiling, it will generate the following JavaScript code.

    var En;(function(En){
    
    En&#91;En&#91;"x"]=0]="x";
    En&#91;En&#91;"y"]=1]="y";
    En&#91;En&#91;"z"]=2]="z";})(En ||(En ={}));functionfunc(obj){return obj.y;}
    console.log(func(En)); console.log(typeof En);

    The output of the above code is as follows

    1
    object
    

    Enums at compile time

    When TypeScript enums are compiled, they are converted to JavaScript objects. The object will have a property for each enum member, and the value of each property will be the enum member’s value.

    The numeric and string enum members behave differently at the compilation. The numeric members are mapped bi-directionally to its corresponding JavaScript object property while string members are mapped uni-directionally to its runtime object property.

    enum Enum {
      Name ='John Doe',
      Age =32,}

    The above TypeScript code will be compiled to the following JavaScript code

    var Enum;(function(Enum){
    
    Enum&#91;"Name"]="John Doe";
    Enum&#91;Enum&#91;"Age"]=32]="Age";})(Enum ||(Enum ={}));</code></pre>

    Please note that the after compilation, the Name member get mapped unidirectionally and Age member get mapped bi-directionally to its corresponding runtime object properties.

    Const Enums

    The const enums are special enums in TypeScript that are completely removed during the compilation. These emums are not included in the compiled JavaScript output.

    Reverse Mapping

    As discussed above that the numeric enum members after compilation get mapped bidirectionally with its runtime object property. This is known as reverse mapping.

    enum Enum {A=1,}console.log(Enum.A)console.log(Enum['A'])console.log(Enum[1]);

    On compiling, it will generate the following JavaScript code.

    var Enum;(function(Enum){
    
    Enum&#91;Enum&#91;"A"]=1]="A";})(Enum ||(Enum ={}));
    console.log(Enum.A); console.log(Enum['A']); console.log(Enum[1]);

    The output of the above code is as follows

    1
    1
    A
    

    Ambient enums

    In TypeScript, ambient enums are used to describe the shape of the already existing enum types. The ambient enums don't generate any JavaScript code. To declare an ambient enum, you can use the declare keyword. Look at the below example

    declareenum Fruit {
    
    Apple,
    Orange,
    Banana,}</code></pre>

    The above code declares the shape of the enum without generating the JavaScript code. It means you can use the Fruit enum in TypeScript code but will not be included in compiled JavaScript code.

    Object vs. Enums

    An object with as const could suffice the need of the enums. So in modern TypeScript, you may not need enums. When an object could work as enums why to use a different type and also the objects align the state of the JavaScript.

    Let's look at the examples of enums and object with as const.

    // enumenum EWeekend {  
      Saturday,  
      Sunday,}console.log(EWeekend.Saturday)// object with as constconst OWeekend ={
    
    Saturday:0,
    Sunday:1,}asconst;console.log(OWeekend.Saturday);</code></pre>

    On compiling, it will generate the following JavaScript code

    // enumvar EWeekend;(function(EWeekend){
    
    EWeekend&#91;EWeekend&#91;"Saturday"]=0]="Saturday";
    EWeekend&#91;EWeekend&#91;"Sunday"]=1]="Sunday";})(EWeekend ||(EWeekend ={}));
    console.log(EWeekend.Saturday);// object with as constconst OWeekend ={
    Saturday:0,
    Sunday:1,};
    console.log(OWeekend.Saturday);

    The output of the above example code is as follows

    0
    0
    

    Using enum as a function parameter

    We can use the enum as a parameter in the function definition.

    enum Color {
      Red,
      Green,
      Blue,}functionprintColor(color: Color):void{console.log(color);}printColor(Color.Red);// Prints 0 to the console

    In the above example, the function printColor() takes a parameter of type Color. It returns nothing but logs the color in the console.

    On compiling, it will generate the following JavaScript code

    var Color;(function(Color){
    
    Color&#91;Color&#91;"Red"]=0]="Red";
    Color&#91;Color&#91;"Green"]=1]="Green";
    Color&#91;Color&#91;"Blue"]=2]="Blue";})(Color ||(Color ={}));functionprintColor(color){
    console.log(color);}printColor(Color.Red);// Prints 0 to the console</code></pre>

    The above example code will produce the following output

    0
    
  • 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

    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.

    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

    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

    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

    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

    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

    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

    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

    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

    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

    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.

    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