TypeScript Interview Questions (2025)

1) What is Typescript?

TypeScript is an open-source programming language that is both free and developed by Microsoft. It serves as a strongly typed superset of JavaScript, which compiles down to standard JavaScript. This language is designed for large-scale JavaScript application development. Developers who have experience with C#, Java, and other strongly typed languages will find TypeScript relatively straightforward to learn and utilize.

TypeScript can be run on any web browser, any host environment, and any operating system. It is not executed directly in the browser; instead, it requires a compiler to transform and produce a JavaScript file. TypeScript represents the ES6 iteration of JavaScript, incorporating various enhanced features.

2) How is TypeScript different from JavaScript?

TypeScript is different from JavaScript in the following manner:

SN JavaScript TypeScript
1 It was developed by Netscape in 1995. It was developed by Anders Hejlsberg in 2012.
2 JavaScript source file is in ".js" extension. TypeScript source file is in ".ts" extension.
3 JavaScript doesn't support ES6. TypeScript supports ES6.
4 It doesn't support strongly typed or static typing. It supports strongly typed or static typing feature.
5 It is just a scripting language. It supports object-oriented programming concept like classes, interfaces, inheritance, generics, etc.
6 JavaScript has no optional parameter feature. TypeScript has optional parameter feature.
7 It is interpreted language that's why it highlighted the errors at runtime. It compiles the code and highlighted errors during the development time.
8 JavaScript doesn't support modules. TypeScript gives support for modules.
9 In this, number, string are the objects. In this, number, string are the interface.
10 JavaScript doesn't support generics. TypeScript supports generics.

To know more click here .

3) Why do we need TypeScript?

We need TypeScript:

  • TypeScript is fast, simple, and most importantly, easy to learn.
  • TypeScript supports object-oriented programming features such as classes, interfaces, inheritance, generics, etc.
  • TypeScript provides the error-checking feature at compilation time. It will compile the code, and if any error found, then it highlighted the errors before the script is run.
  • TypeScript supports all JavaScript libraries because it is the superset of JavaScript.
  • TypeScript support reusability by using the inheritance.
  • TypeScript make app development quick and easy as possible, and the tooling support of TypeScript gives us autocompletion, type checking, and source documentation.
  • TypeScript supports the latest JavaScript features including ECMAScript 2015.
  • TypeScript gives all the benefits of ES6 plus more productivity.
  • TypeScript supports Static typing, Strongly type, Modules, Optional Parameters, etc.
  • 4) List some features of Typescript?

To know more click here .

5) List some benefits of using Typescript?

TypeScript has the following benefits.

  • It provides the benefits of optional static typing. Here, Typescript provides types that can be added to variables, functions, properties, etc.
  • Typescript has the ability to compile down to a version of JavaScript that runs on all browsers.
  • TypeScript always highlights errors at compilation time during the time of development whereas JavaScripTypeScript Tutorials out errors at the runtime.
  • TypeScript supports strongly typed or static typing whereas this is not in JavaScript.
  • It helps in code structuring.
  • It uses class-based object-oriented programming.
  • It provides excellent tooling supports with IntelliSense which provides active hints as the code is added.
  • It has a namespace concept by defining a module.
  • 6) What are the disadvantages of TypeScript?

TypeScript has the following disadvantages:

  • TypeScript takes a long time to compile the code.
  • TypeScript does not support abstract classes.
  • If we run the TypeScript application in the browser, a compilation step is required to transform TypeScript into JavaScript.
  • Web developers are using JavaScript from decades and TypeScript doesn?t bring anything new.
  • To use any third party library, the definition file is must. And not all the third party library have definition file available.
  • Quality of type definition files is a concern as for how can you be sure the definitions are correct?
  • 7) What are the different components of TypeScript?

TypeScript primarily consists of three key components. These include-

Language

The language includes components such as novel syntax, keywords, type annotations, and enables us to develop in TypeScript.

Compiler

The TypeScript compiler is an open-source, cross-platform tool developed in TypeScript. It converts TypeScript code into its JavaScript counterpart. The compiler undertakes parsing and type verification of the TypeScript code before producing the JavaScript output. Additionally, it can merge multiple files into a single output file and generate source maps.

Language Service

The language service delivers information that aids editors and various tools in offering enhanced support functionalities, including automated refactoring and IntelliSense.

To know more click here .

8) Who developed Typescript and what is the current stable version of Typescript?

TypeScript was created by Anders Hejlsberg, a prominent member of the C# language development team. The initial release of TypeScript occurred on October 1, 2012, and it was designated as version 0.8. Microsoft is responsible for its development and ongoing maintenance, operating under the Apache 2 license. It was specifically crafted for the creation of extensive applications.

The stable version of TypeScript at present is 3.2, which debuted on September 30, 2018. TypeScript is designed to compile into straightforward JavaScript code, compatible with any browser that adheres to the ECMAScript 2015 specification. It provides support for contemporary and developing JavaScript functionalities.

9) Tell the minimum requirements for installing Typescript. OR how can we get TypeScript and install it?

TypeScript can be installed and handled through Node.js using npm, the Node.js package manager. To set up TypeScript, begin by verifying that npm is properly installed, and then execute the subsequent command to install TypeScript globally on your system.

Example

$ npm install -g typescript

It installs a command line utility "tsc" that will subsequently be utilized for compiling our Typescript code. Ensure that we verify the version of Typescript present on the system.

Following steps are involved for installing TypeScript:

  • Download and run the .msi installer for the node.
  • Enter the command "node -v" to check if the installation was successful.
  • Type the following command in the terminal window to install Typescript: $ npm install -g typescript

To know installation process click here .

10) List the built-in types in Typescript.

In TypeScript, the native data types are referred to as primitive data types. The following list outlines these types.

Number type: This is utilized to represent values of the number type. In TypeScript, all numerical values are stored as floating point representations.

Syntax: let identifier: number = value;

String type: It denotes a series of characters encoded in Unicode UTF-16 format. We incorporate string literals into our scripts by surrounding them with either single or double quotation marks.

Syntax: let identifier: string = " ";

Boolean type: This is utilized to denote a logical value. When employing the Boolean type, the output is restricted to either true or false. A Boolean value represents a truth value that indicates the veracity of a condition.

Syntax: let identifier: bool = Boolean value;

Null type: Null signifies a variable with an undefined value. Directly referencing the null type value itself is not feasible. The null type lacks utility since it can only be assigned a null value.

Syntax: let num: number = null;

Undefined type: This refers to the type of an undefined literal. The Undefined type signifies all variables that have not been initialized. Its utility is limited since it allows for the assignment of only an undefined value. This built-in type serves as a sub-type for all other types.

Syntax: let num: number = undefined;

Void type: The void type serves as the return type for functions that do not yield any value. It is utilized in scenarios where there is no applicable datatype.

Syntax: let unusable: void = undefined;

For an in-depth understanding of TypeScript data types, click here.

11) What are the variables in Typescript? How to create a variable in Typescript?

A variable is the storage location, which is used to store value/information to be referenced and used by programs. It acts as a container for value in a program. It can be declared using the var keyword. It should be declared before the use. While declaring a variable in Typescript, certain rules should be followed-

  • The variable name must be an alphabet or numeric digits.
  • The variable name cannot start with digits.
  • The variable name cannot contain spaces and special character, except the underscore(_) and the dollar($) sign.

We can declare a variable in one of the four ways:

  • Declare type and value in a single statement. Syntax: var [identifier] : [type-annotation] = value;
  • Declare type without value. Syntax: var [identifier] : [type-annotation];
  • Declare its value without type. Syntax: var [identifier] = value;
  • Declare without value and type. Syntax: var [identifier];

For further information, please click here. https://www.logic practice.com/typescript-variables

12) How to compile a Typescript file?

Below is the command utilized for converting a Typescript file into JavaScript.

Example

$ tsc <TypeScript File Name>

For example, to compile "Helloworld.ts."

Example

$ tsc helloworld.ts

The result would be helloworld.js.

13) Is it possible to combine multiple .ts files into a single .js file? If yes, then how?

Indeed, it is feasible. To achieve this, it is necessary to include the --outFILE [OutputJSFileName] compilation option.

Example

$ tsc --outFile comman.js file1.ts file2.ts file3.ts

The command mentioned above will compile all three ".ts" files, with the output being saved in a single "comman.js" file. This occurs when an output file name is not specified, as demonstrated in the command below.

Example

$ tsc --outFile file1.ts file2.ts file3.ts

Subsequently, file2.ts and file3.ts will undergo compilation, with the resulting output being directed into file1.ts. As a result, file1.ts now holds JavaScript code.

14) Is it possible to compile .ts automatically with real-time changes in the .ts file?

Indeed, it is feasible to compile ".ts" files automatically while reflecting real-time modifications in the .ts document. This can be accomplished by utilizing the --watch compiler option.

Example

tsc --watch file1.ts

The command mentioned above initially compiles file1.ts into file1.js and monitors the file for any alterations. If any changes are identified, it will recompile the file. It is important to note that the command prompt should remain open while executing the command with the --watch option.

15) What do you mean by interfaces? Explain them with reference to Typescript.

An Interface serves as a framework within our application, functioning as a contract. It stipulates the syntax that classes must adhere to, meaning any class that implements an interface is obligated to define all its members. While it cannot be instantiated, it can be referenced through the class object that implements it. The TypeScript compiler employs interfaces for type-checking (often referred to as "duck typing" or "structural subtyping") to determine whether an object possesses a particular structure.

Syntax:

Example

interface interface_name {  

          // variables' declaration  

          // methods' declaration  

}

The interface solely defines the methods and fields. It is not capable of being utilized to construct any components. Interfaces do not require conversion into JavaScript for execution purposes. They have no effect on runtime JavaScript. Consequently, their sole function is to assist during the development phase.

16) What do you understand by classes in Typescript? List some features of classes.

TypeScript is recognized as an Object-Oriented JavaScript language that incorporates OOP features such as classes and interfaces. Similar to Java, classes serve as the essential building blocks for developing reusable components. A class consists of a collection of objects that share common attributes. It acts as a template or blueprint for generating objects and represents a logical construct. The declaration of a class in TypeScript is accomplished using the "class" keyword.

Example:

Example

class Student {  

    studCode: number;  

    studName: string;  

    constructor(code: number, name: string) {  

            this.studName = name;  

            this.studCode = code;  

    }  

    getGrade() : string {  

        return "A+" ;  

    }  

}

Features of a class are-

  • Inheritance
  • Encapsulation
  • Polymorphism
  • Abstraction
  • 17) Is Native Javascript supports modules?

At present, Native JavaScript does not offer support for modules. To develop and utilize modules in JavaScript, it is necessary to use an external system such as CommonJS.

18) Which object oriented terms are supported by TypeScript?

TypeScript supports following object oriented terms.

  • Modules
  • Classes
  • Interfaces
  • Inheritance
  • Data Types
  • Member functions
  • 19) How to Call Base Class Constructor from Child Class in TypeScript?

The super function is utilized to invoke the constructor of the parent or base class from within a Child Class.

20) How do you implement inheritance in TypeScript?

Inheritance is a process that allows one class to obtain the attributes and behaviors of another class. This concept is fundamental in object-oriented programming languages and facilitates the creation of new classes based on pre-existing ones. The class that provides its members for inheritance is referred to as the base class, while the class that inherits these members is known as the derived class.

Inheritance can be realized through the use of the extend keyword. This concept can be illustrated with the following example.

Example

class Shape {   

   Area:number   

   constructor(area:number) {   

      this.Area = area  

   }   

}   

class Circle extends Shape {   

   display():void {   

      console.log("Area of the circle: "+this.Area)   

   }   

}  

var obj = new Circle(320);   

obj.display()  //Output: Area of the circle: 320

To know more click here .

21) What are the Modules in Typescript?

A module serves as an effective method for grouping associated variables, functions, classes, interfaces, and more. It operates within its specific scope, rather than the global scope. To put it differently, the variables, functions, classes, and interfaces defined within a module are not directly accessible from outside that module.

Creating a Module

A module is formed by utilizing the export keyword and can be accessed in other modules through the import keyword.

Example

module module_name{

	class xyz{

		export sum(x, y){

		 	return x+y;

		 }

	}

}

To know more click here .

22) What is the difference between the internal module and the external module?

The difference between internal and external module is given below:

| 5 | Example:module Sum {

SN Internal Module External Module
1 Internal modules were used to logically group the classes, interfaces, functions, variables into a single unit and can be exported in another module. External modules are useful in hiding the internal statements of the module definitions and show only the methods and parameters associated with the declared variable.
2 Internal modules were in the earlier version of Typescript. But they are still supported by using namespace in the latest version of TypeScript. External modules are simply known as a module in the latest version of TypeScript.
3 Internal modules are local or exported members of other modules (including the global module and external modules). External modules are separately loaded bodies of code referenced using external module names.
4 Internal modules are declared using ModuleDeclarations that specify their name and body. An external module is written as a separate source file that contains at least one import or export declaration.

export function add(a, b) {

console.log("Sum: " +(a+b));

}

} | Example:export class Addition{

constructor(private xCoordinate?: number, private yCoordinate?: number){

}

Sum{

console.log("SUM: " +(this.x + this.y));

}

} |

Example

module Sum {   

   export function add(a, b) {    

      console.log("Sum: " +(a+b));   

   }   

}
Example

export class Addition{  

    constructor(private x?: number, private y?: number){  

    }  

    Sum(){  

        console.log("SUM: " +(this.x + this.y));  

    }  

}

To know more in detail click here .

23) What is namespace in Typescript? How to declare a namespace in Typescript?

A namespace serves as a method for organizing functionalities logically. It is utilized for the internal management of legacy TypeScript code. Namespaces encapsulate features and objects that possess specific connections. Also referred to as internal modules, a namespace can encompass interfaces, classes, functions, and variables to facilitate a collection of related functionalities.

Note: A namespace can be defined in multiple files and allow to keep each file as they were all defined in one place. It makes code easier to maintain.

Synatax for creating namespace

Example

namespace <namespace_name> {  

           export interface I1 { }  

           export class c1{ }  

}

To know more click here .

24) Explain Decorators in Typescript?

A Decorator represents a unique type of declaration that may be utilized on classes, methods, accessors, properties, or parameters. Essentially, decorators are functions that are preceded by the @expression symbol, with the expression required to resolve to a function that will be invoked during runtime, providing details about the decorated declaration.

TypeScript Decorators are designed to append annotations and metadata to existing code in a declarative manner. This feature is experimental and was proposed for ES7. Several JavaScript frameworks, such as Angular 2, are already utilizing decorators. Future updates may alter the implementation of decorators.

To activate experimental support for decorators, we need to set the experimentalDecorators compiler option either via the command line or within our tsconfig.json file:

Command Line

Example

$tsc --target ES5 --experimentalDecorators

tsconfig.json

Example

{  

    "compilerOptions": {  

        "target": "ES5",  

        "experimentalDecorators": true  

    }  

}

To know more click here .

25) What are Mixins?

In JavaScript, mixins provide a method for constructing classes using reusable components by merging simpler, partial classes known as mixins.

The concept is straightforward: rather than having class A inherit from class B to acquire its features, function B accepts class A as an argument and produces a new class that incorporates this additional functionality. Function B acts as a mixin.

26) What is default visibility for properties/methods in TypeScript classes?

In TypeScript classes, the default visibility for properties and methods is set to public.

27) How does TypeScript support optional parameters in function as in JavaScript every parameter is optional for a function?

In contrast to JavaScript, the TypeScript compiler generates an error when a function is called without the precise quantity and types of arguments specified in its function signature. To address this issue, we can implement optional parameters by placing a question mark ('?') next to them. This indicates that the parameters that might not have a value can be suffixed with a '?' to denote their optional nature.

Example

function Demo(arg1: number, arg2? :number) {            

}So, arg1 is always required, and arg2 is an optional parameter.

Therefore, arg1 is mandatory, while arg2 is considered an optional argument.

Note: Optional parameters must follow the required parameters. If we want to make arg1 optional, instead of arg2, then we need to change the order and arg1 must be put after arg2.

Example

function Demo(arg2: number, arg1? :number) {

}

To know more click here .

28) Does TypeScript supports function overloading as JavaScript doesn't support function overloading?

Indeed, TypeScript allows for function overloading; however, the way it is executed is somewhat unconventional. In TypeScript, when utilizing function overloading, one can define a single function that has multiple signatures.

Example

//Function with string type parameter  

function add(a:string, b:string): string;  

//Function with number type parameter  

function add(a:number, b:number): number;  

//Function Definition  

function add(a: any, b:any): any {  

    return a + b;  

}

In the example provided, the initial two lines represent the function overload declarations. There are two distinct overloads: the first signature accepts a parameter of type string, while the second one takes a parameter of type number. The third function features the concrete implementation and utilizes a parameter of type any, which allows for any data type to be passed. The implementation subsequently verifies the type of the provided parameter and executes different code segments according to the type of the supplied parameter.

29) Is it possible to debug any TypeScript file?

Indeed, it is feasible. To troubleshoot any TypeScript file, a corresponding .js source map file is required. Therefore, compile the .ts file using the --sourcemap option to produce a source map file.

Example

$ tsc -sourcemap file1.ts

This will generate file1.js and file1.js.map. Additionally, the final line of file1.js will include a reference to the source map file.

Example

//# sourceMappingURL=file1.js.map

30) What is TypeScript Definition Manager and why do we need it?

The TypeScript Definition Manager (TSD) serves as a package manager that enables users to locate and install TypeScript definition files straight from the community-supported DefinitelyTyped repository.

Imagine that we wish to incorporate certain jQuery functionality within our .ts file.

Example

$(document).ready(function() { //Your jQuery code });

At this point, if we attempt to compile the code using tsc, we will encounter a compile-time error stating: Cannot find the name "$". Therefore, we must notify the TypeScript compiler that "$" is associated with jQuery. This is where TSD becomes useful. We can obtain the jQuery Type Definition file and incorporate it into our .ts file. The following are the steps to accomplish this:

First, install TSD.

Example

$ npm install tsd -g

Within the TypeScript directory, initiate a new TypeScript project by executing:

Example

$ tsd init

Then install the definition file for jQuery.

Example

tsd query jquery --action install

The command provided will retrieve and establish a new directory that houses the jQuery definition file, which concludes with ".d.ts". Subsequently, incorporate the definition file by modifying the TypeScript file to reference the jQuery definition.

Example

/// <reference path="typings/jquery/jquery.d.ts" />

$(document).ready(function() { //To Do

});

Now, recompile. This time, the JavaScript file will be produced without any errors. Therefore, the necessity of TSD assists us in obtaining the type definition file for the specified framework.

31) What is TypeScript Declare Keyword?

It is understood that not all JavaScript libraries or frameworks provide TypeScript declaration files; however, we aim to incorporate them within our TypeScript file without encountering compilation errors. To achieve this, we utilize the declare keyword. This keyword serves for ambient declarations and methods, allowing us to specify a variable that might be defined in another context.

For instance, consider a library named myLibrary that lacks a TypeScript declaration file and contains a namespace called myLibrary in the global scope. To utilize this library within our TypeScript program, we can employ the following code:

Example

declare var myLibrary;

At runtime, TypeScript will designate the myLibrary variable with the any type. This presents an issue where we will lack Intellisense during design time; however, we will still have the capability to utilize the library within our code.

32) How to generate TypeScript definition file from any .ts file?

By utilizing the tsc compiler, we can create a TypeScript definition file from any .ts file. This process produces a TypeScript definition that enhances the reusability of our TypeScript file.

Example

tsc --declaration file1.ts

33) What is tsconfig.json file?

The tsconfig.json file is structured in JSON format. Within this file, we can define several options to instruct the compiler on how to compile the existing project. The existence of a tsconfig.json file in a directory signifies that the directory serves as the root of a TypeScript project. Below is an example of a tsconfig.json file.

Example

{

   "compilerOptions": {

      "declaration": true,    

      "emitDecoratorMetadata": false,    

      "experimentalDecorators": false,    

      "module": "none",    

      "moduleResolution": "node"

      "removeComments": true,

      "sourceMap": true

   },

   "files": [

      "main.ts",

      "othermodule.ts"

    ]

}

To know more click here .

34) Explain generics in TypeScript?

TypeScript Generics serves as a mechanism for developing reusable components. It enables the creation of components that can operate with multiple data types instead of being restricted to just one. Generics ensure type safety while maintaining performance and productivity. With Generics, we can define generic classes, generic functions, generic methods, and generic interfaces.

In generics, a type parameter is enclosed within the open (<) and close (>) brackets, resulting in strongly typed collections. Generics utilize a specific type variable <T> that signifies types. The collections generated through generics consist exclusively of homogeneous object types.

Example

function identity<T>(arg: T): T {    

    return arg;    

}    

let output1 = identity<string>("myString");    

let output2 = identity<number>( 100 );  

console.log(output1);  

console.log(output2);

To know more click here .

35) Does TypeScript support all object-oriented principles?

Yes, TypeScript support all object-oriented principles. There are four main principles to object-oriented programming:

  • Encapsulation,
  • Inheritance,
  • Abstraction, and
  • Polymorphism.
  • 36) How to check null and undefined in TypeScript?

Employing a juggling-check allows us to verify both null and undefined values:

Example

if (x == null) {

}

When employing a strict check, it will consistently return true for values assigned to null and will not evaluate to true for variables that are undefined.

Example

Example

var a: number;

var b: number = null;

function check(x, name) {

    if (x == null) {

        console.log(name + ' == null');

    }

    if (x === null) {

        console.log(name + ' === null');

    }

    if (typeof x === 'undefined') {

        console.log(name + ' is undefined');

    }

}

check(a, 'a');

check(b, 'b');

Output

Output

"a == null"

"a is undefined"

"b == null"

"b === null"

37) Could we use TypeScript on the backend? If yes, how?

Absolutely, TypeScript can be utilized on the backend. This can be illustrated through the following example. In this case, we opt for Node.js, which provides enhanced type safety along with the other abstractions that the language offers.

  • Install TypeScript compiler
  • Example
    
    npm i -g typescript
    
  • The TypeScript compiler utilizes settings specified in the tsconfig.json file. This configuration file dictates the location for the output of compiled files.
  • Example
    
    {
    
      "compilerOptions": {
    
        "target": "es5",
    
        "module": "commonjs",
    
        "declaration": true,
    
        "outDir": "build"
    
      }
    
    }
    
  • Compile ts files
  • Example
    
    node build/index.js
    

    38) What is the difference between "interface vs type" statements?

    Example
    
    interface X {
    
        a: number
    
        b: string
    
    }
    
    type X = {
    
        a: number
    
        b: string
    
    };
    
SN interface type
1 An interface declaration always introduces a named object type. A type alias declaration can introduce a name for any kind of type, including primitive, union, and intersection types.
2 An interface can be named in an extends or implements clause. Type alias for an object type literal cannot be named in an extends or implements clause.
3 Interfaces create a new name that is used everywhere. Type aliases don't create a new name.
4 An interface can have multiple merged declarations. Type alias for an object type literal cannot have multiple merged declarations.

39) What are Ambients in TypeScripts and when to use them?

Ambient declarations inform the compiler that the corresponding source code is located externally. If these source codes are not present during runtime and an attempt is made to utilize them, it will result in a failure without any prior notification.

Ambient declaration files resemble documentation files. Should the source be modified, it is essential to keep the documentation current as well. Failing to update the ambient declaration file will result in compiler errors.

The Ambient declarations enable us to utilize well-known JavaScript libraries such as jQuery, AngularJS, Node.js, and others with safety and ease.

40) What is a TypeScript Map file?

  • TypeScript Map file is a source map file which holds information about our original files.
  • .map files are source map files that let tools map between the emitted JavaScript code and the TypeScript source files that created it.
  • Many debuggers can consume these files so we can debug the TypeScript file instead of the JavaScript file.
  • 41) What is Type assertions in TypeScript?

Type assertion functions similarly to typecasting found in other programming languages; however, it does not engage in type verification or data reformulation as seen in languages such as C# and Java. While typecasting includes runtime support, type assertion does not influence runtime behavior. Instead, type assertions are utilized exclusively by the compiler, offering guidance on how we wish our code to be interpreted.

Example

Example

let empCode: any = 111;   

let employeeCode = <number> code;   

console.log(typeof(employeeCode)); //Output: number

To know more click here .

42) What is "as" syntax in TypeScript?

The as syntax serves as the supplementary method for type assertion in TypeScript. This as-syntax was introduced due to conflicts arising between the original syntax (<type>) and JSX.

Example

Example

let empCode: any = 111;   

let employeeCode = code as number;

In TypeScript combined with JSX, only assertions in the form of 'as' are permitted.

43) What is JSX? Can we use JSX in TypeScript?

JSX is essentially JavaScript with an altered file extension. This new extension was developed by Facebook to differentiate it from the XML-like representation of HTML within JavaScript.

JSX is a syntax that resembles XML and can be embedded within JavaScript code. Its purpose is to be converted into valid JavaScript. JSX gained widespread recognition alongside the React framework. TypeScript facilitates the embedding, type validation, and direct compilation of JSX into JavaScript.

In order to utilize JSX, we need to accomplish two tasks.

  • Assign a .tsx extension to the files
  • Activate the jsx option
  • 44) What is Rest parameters?

The rest parameter enables the transmission of zero or more arguments to a function. It is defined by placing three dot characters ('...') in front of the parameter name. This feature permits functions to accept a flexible number of arguments without relying on the arguments object. It proves particularly beneficial in scenarios where the exact count of parameters is unknown.

Rules to follow in rest parameter:

  • Only one rest parameter is allowed in a function.
  • It must be an array type.
  • It must be a last parameter in the parameter list.
  • Example
    
    function sum(a: number, ...b: number[]): number {  
    
     let result = a;  
    
     for (var i = 0; i < b.length; i++) {  
    
     result += b[i];  
    
     }  
    
     console.log(result);  
    
    }  
    
    let result1 = sum(3, 5);  
    
    let result2 = sum(3, 5, 7, 9);
    

To know more click here .

45) Explain Enum in TypeScript?

Enums, or enumerations, represent a TypeScript data type that enables the definition of a collection of named constants. The utilization of enums can enhance the clarity of intent or establish a set of unique cases. They consist of a group of associated values, which may be either numeric or string types.

Example

Example

enum Gender {

  Male,

  Female

  Other

}

console.log(Gender.Female); // Output: 1

//We can also access an enum value by it's number value.

console.log(Gender[1]); // Output: Female

46) Explain Relative vs. Non-relative module imports.

| A non-relative import can be resolved relative to baseUrl, or through path mapping. In other words, we use non-relative paths when importing any of our external dependencies.Example:import * as $ from "jquery";

Non-Relative Relative

import { Component } from "@angular/core"; | Relative imports can be employed for our custom modules that are assured to retain their relative positioning during runtime. A relative import begins with /, ./, or ../. For instance: import Entry from "./components/Entry";

import {DefaultHeaders} from "../constants/http";

Example

import * as $ from "jquery";

import { Component } from "@angular/core";
Example

import Entry from "./components/Entry";

import {DefaultHeaders} from "../constants/http";

47) What is an anonymous function?

An anonymous function refers to a function that is defined without a specific name. These functions are instantiated at runtime. Similar to regular functions, anonymous functions can take parameters and yield results. Typically, an anonymous function is not available for use after its creation.

Example

Example

let myAdd = function(x: number, y: number): number { 

return x + y; 

};

console.log(myAdd())

48) What is Declaration Merging?

Declaration merging refers to the method employed by the compiler to combine multiple distinct declarations. Declarations that share the same name are unified into a singular definition. This unified definition incorporates the characteristics of both original declarations.

The most straightforward, and likely the most prevalent, form of declaration merging is the merging of interfaces. At its core, this process combines the members from both declarations into a unified interface that shares the same name.

Example

Example

interface Cloner {

    clone(animal: Animal): Animal;

}

interface Cloner {

    clone(animal: Sheep): Sheep;

}

interface Cloner {

    clone(animal: Dog): Dog;

    clone(animal: Cat): Cat;

}

The three interfaces will combine to form a unified declaration as follows:

Example

interface Cloner {

    clone(animal: Dog): Dog;

    clone(animal: Cat): Cat;

    clone(animal: Sheep): Sheep;

    clone(animal: Animal): Animal;

}

Note: Not all merges are allowed in TypeScript. Currently, classes can not merge with other classes or variables.

49) What are method overriding in TypeScript?

When a subclass (or child class) contains a method that matches one defined in its parent class, this is referred to as method overriding. In essence, it involves redefining the methods from the base class within the derived class or child class.

Rules for Method Overriding

  • The method must have the same name as in the parent class
  • The method must have the same parameter as in the parent class.
  • There must be an IS-A relationship (inheritance).

Example

Example

class NewPrinter extends Printer {

    doPrint(): any {

        super.doPrint();

        console.log("Called Child class.");

    }

    doInkJetPrint(): any {

        console.log("Called doInkJetPrint().");

    }

}

let printer: new () => NewPrinter;

printer.doPrint();

printer.doInkJetPrint();

50) What is Lambda/Arrow function?

The ES6 iteration of TypeScript introduces a concise notation for creating anonymous functions, commonly referred to as function expressions. These arrow functions, also known as Lambda functions, are characterized by their lack of a designated name. The arrow function syntax eliminates the need for the function keyword.

Example

Example

let sum = (a: number, b: number): number => {  

            return a + b;  

}  

console.log(sum(20, 30)); //returns 50

In the preceding context, the ?=>? represents a lambda operator, while (a + b) constitutes the function's body, and (a: number, b: number) are the parameters defined inline.

To know more click here .

Input Required

This code uses input(). Please provide values below: