Live Classes: Upskill your knowledge Now!
Chat NowPublished - Tue, 06 Dec 2022
A list of top frequently asked TypeScript Interview Questions and answers are given below.
TypeScript is a free and open-source programming language developed and maintained by Microsoft. It is a strongly typed superset of JavaScript that compiles to plain JavaScript. It is a language for application-scale JavaScript development. TypeScript is quite easy to learn and use for developers familiar with C#, Java and all strong typed languages.
TypeScript can be executed on Any browser, Any Host, and Any Operating System. TypeScript is not directly run on the browser. It needs a compiler to compile and generate in JavaScript file. TypeScript is the ES6 version of JavaScript with some additional features.
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.
We need TypeScript:
To know more click here.
TypeScript has the following benefits.
TypeScript has the following disadvantages:
The TypeScript has mainly three components. These are-
Language
The language comprises elements like new syntax, keywords, type annotations, and allows us to write TypeScript.
Compiler
The TypeScript compiler is open source, cross-platform, and is written in TypeScript. It transforms the code written in TypeScript equivalent to its JavaScript code. It performs the parsing, type checking of our TypeScript code to JavaScript code. It can also help in concatenating different files to the single output file and in generating source maps.
Language Service
The language service provides information which helps editors and other tools to give better assistance features such as automated refactoring and IntelliSense.
To know more click here.
The typescript was developed by Anders Hejlsberg, who is also one of the core members of the development team of C# language. The typescript was first released in the month of October 1st, 2012 and was labeled version 0.8. It is developed and maintained by Microsoft under the Apache 2 license. It was designed for the development of a large application.
The current stable version of TypeScript is 3.2 which was released on September 30, 2018. Typescript compiles to simple JavaScript code which runs on any browser that supports ECMAScript 2015 framework. It offers support for the latest and evolving JavaScript features.
TypeScript can be installed and managed with the help of node via npm (the Node.js package manager). To install TypeScript, first ensure that the npm is installed correctly, then run the following command which installs TypeScript globally on the system.
It installs a command line code "tsc" which will further be used to compile our Typescript code. Make sure that we check the version of Typescript installed on the system.
Following steps are involved for installing TypeScript:
To know installation process click here.
The built-in data types are also known as primitive data types in Typescript. These are given below.
Number type: It is used to represent number type values. All the numbers in TypeScript are stored as floating point values.
Syntax: let identifier: number = value;
String type: It represents a sequence of characters stored as Unicode UTF-16 code. We include string literals in our scripts by enclosing them in single or double quotation marks.
Syntax: let identifier: string = " ";
Boolean type: It is used to represent a logical value. When we use the Boolean type, we get output only in true or false. A Boolean value is a truth value that specifies whether the condition is true or not.
Syntax: let identifier: bool = Boolean value;
Null type: Null represents a variable whose value is undefined. It is not possible to directly reference the null type value itself. Null type is not useful because we can only assign a null value to it.
Syntax: let num: number = null;
Undefined type: It is the type of undefined literal. The Undefined type denotes all uninitialized variables. It is not useful because we can only assign an undefined value to it. This type of built-in type is the sub-type of all the types.
Syntax: let num: number = undefined;
Void type: A void is the return type of the functions that do not return any type of value. It is used where no datatype is available.
Syntax: let unusable: void = undefined;
To know TypeScript datatypes in detail click here.
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-
We can declare a variable in one of the four ways:
To know more in detail click here.https://www.javatpoint.com/typescript-variables
Here is the command which is followed while compiling a Typescript file into JavaScript.
For example, to compile "Helloworld.ts."
The result would be helloworld.js.
Yes, it is possible. For this, we need to add --outFILE [OutputJSFileName] compiling option.
The above command will compile all three ".ts"file and result will be stored into single "comman.js" file. In the case, when we don't provide an output file name as like in below command.
Then, the file2.ts and file3.ts will be compiled, and the output will be placed in file1.ts. So now our file1.ts contains JavaScript code.
Yes, it is possible to compile ".ts" automatically with real-time changes in the .ts file. This can be achieved by using --watch compiler option
The above command first compiles file1.ts in file1.js and watch for the file changes. If there is any change detected, it will compile the file again. Here, we need to ensure that command prompt must not be closed on running with --watch option.
An Interface is a structure which acts as a contract in our application. It defines the syntax for classes to follow, it means a class that implements an interface is bound to implement all its members. It cannot be instantiated but can be referenced by the class object that implements it. The TypeScript compiler uses interface for type-checking (also known as "duck typing" or "structural subtyping") whether the object has a specific structure or not.
Syntax:
The interface just declares the methods and fields. It cannot be used to build anything. Interfaces need not be converted to JavaScript for execution. They have zero runtime JavaScript impact. Thus, their only purpose is to help in the development stage.
We know, TypeScript is a type of Object-Oriented JavaScript language and supports OOPs programming features like classes, interfaces, etc. Like Java, classes are the fundamental entities which are used to create reusable components. It is a group of objects which have common properties. A class is a template or blueprint for creating objects. It is a logical entity. The "class" keyword is used to declare a class in Typescript.
Example:
Features of a class are-
No. Currently, modules are not supported by Native JavaScript. To create and work with modules in Javascript we require an external like CommonJS.
TypeScript supports following object oriented terms.
super() function is used to called parent or base class constructor from Child Class.
Inheritance is a mechanism that acquires the properties and behaviors of a class from another class. It is an important aspect of OOPs languages and has the ability which creates new classes from an existing class. The class whose members are inherited is called the base class, and the class that inherits those members is called the derived class.
An Inheritance can be implemented by using the extend keyword. We can understand it by the following example.
To know more click here.
A module is a powerful way to create a group of related variables, functions, classes, and interfaces, etc. It can be executed within their own scope, not in the global scope. In other words, the variables, functions, classes, and interfaces declared in a module cannot be accessible outside the module directly.
Creating a Module
A module can be created by using the export keyword and can be used in other modules by using the import keyword.
To know more click here.
The difference between internal and external module is given below:
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. |
5 | 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.
A namespace is a way that is used for logical grouping of functionalities. Namespaces are used to maintain the legacy code of typescript internally. It encapsulates the features and objects that share certain relationships. A namespace is also known as internal modules. A namespace can also include interfaces, classes, functions, and variables to support a group of related functionalities.
Synatax for creating namespace
To know more click here.
A Decorator is a special kind of declaration that can be applied to classes, methods, accessor, property, or parameter. Decorators are simply functions that are prefixed @expression symbol, where expression must evaluate to a function that will be called at runtime with information about the decorated declaration.
TypeScript Decorators serves the purpose of adding both annotations and metadata to the existing code in a declarative way. Decorators are an experimental feature proposed for ES7. It is already in use by some of the JavaScript frameworks including Angular 2. The Decorators may change in future releases.
To enable experimental support for decorators, we must enable the experimentalDecorators compiler option either on the command line or in our tsconfig.json:
Command Line
tsconfig.json
To know more click here.
In Javascript, Mixins are a way of building up classes from reusable components is to build them by combining simpler partial classes called mixins.
The idea is simple, instead of a class A extending class B to get its functionality, function B takes class A and returns a new class with this added functionality. Function B is a mixin.
Public is the default visibility for properties/methods in TypeScript classes.
Unlike JavaScript, the TypeScript compiler will throw an error if we try to invoke a function without providing the exact number and types of parameters as declared in its function signature. To overcome this problem, we can use optional parameters by using question mark sign ('?'). It means that the parameters which may or may not receive a value can be appended with a '?' to mark them optional.
So, arg1 is always required, and arg2 is an optional parameter.
To know more click here.
Yes, TypeScript support function overloading. But the implementation is odd. When we perform function overloading in TypeScript, then we can implement only one functions with multiple signatures.
In the above example, the first two lines are the function overload declaration. It has two overloads. The first signature has a parameter of type string whereas the second signature has a parameter of type number. The third function contains the actual implementation and has a parameter of type any. Any data type can take any type of data. The implementation then checks for the type of the supplied parameter and execute a different piece of code based on supplier parameter type.
Yes, it is possible. To debug any TypeScript file, we need .js source map file. So compile the .ts file with the --sourcemap flag to generate a source map file.
This will create file1.js and file1.js.map. And last line of file1.js would be reference of source map file.
TypeScript Definition Manager (TSD) is a package manager used to search and install TypeScript definition files directly from the community-driven DefinitelyTyped repository.
Suppose, we want to use some jQuery code in our .ts file.
Now, when we try to compile it by using tsc, it will give a compile-time error: Cannot find the name "$". So, we need to inform TypeScript compiler that "$" is belongs to jQuery. To do this, TSD comes into play. We can download jQuery Type Definition file and include it in our .ts file. Below are the steps to perform this:
First, install TSD.
In TypeScript directory, create a new TypeScript project by running:
Then install the definition file for jQuery.
The above command will download and create a new directory containing jQuery definition file ends with ".d.ts". Now, include definition file by updating TypeScript file to point to the jQuery definition.
Now, compile again. This time js file will be generated without any error. Hence, the need of TSD helps us to get type definition file for the required framework.
We know that all JavaScript libraries/frameworks don't have TypeScript declaration files, but we want to use them in our TypeScript file without any compilation errors. To do this, we use the declare keyword. The declare keyword is used for ambient declarations and methods where we want to define a variable that may exist elsewhere.
For example, suppose we have a library called myLibrary that doesn't have a TypeScript declaration file and have a namespace called myLibrary in the global namespace. If we want to use that library in our TypeScript code, we can use the following code:
TypeScript runtime will assign the myLibrary variable as any type. Here is a problem that we won't get Intellisense in design time but we will be able to use the library in our code.
We can generate TypeScript definition file from any .ts file by using tsc compiler. It will be generating a TypeScript definition which makes our TypeScript file reusable.
The tsconfig.json file is a file which is in JSON format. In the tsconfig.json file, we can specify various options to tell the compiler how to compile the current project. The presence of a tsconfig.json file in a directory indicates that the directory is the root of a TypeScript project. Below is a sample tsconfig.json file.
To know more click here.
TypeScript Generics is a tool which provides a way to create reusable components. It is able to create components that can work with a variety of data types rather than a single data type. Generics provides type safety without compromising the performance, or productivity. Generics allow us to create generic classes, generic functions, generic methods, and generic interfaces.
In generics, a type parameter is written between the open (<) and close (>) brackets which makes it strongly typed collections. Generics use a special kind of type variable
To know more click here.
Yes, TypeScript support all object-oriented principles. There are four main principles to object-oriented programming:
By using a juggling-check, we can check both null and undefined:
If we use a strict-check, it will always true for values set to null and won't evaluate as true for undefined variables.
Example
Output
Yes, we can use TypeScript on the backend. We can understand it with the following example. Here, we choose Node.js and have some additional type safety and the other abstraction that the language brings.
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. |
Ambient declarations tell the compiler about the actual source code exist elsewhere. If these source codes do not exist at runtime and we try to use them, then it will break without warning.
Ambient declarations files are like docs file. If the source changes, the docs need to be kept updated also. If the ambient declaration file is not updated, then we will get compiler errors.
The Ambient declarations allow us to safely and easily use existing popular JavaScript libraries like jquery, angularjs, nodejs, etc.
Type assertion works like a typecasting in other languages, but it doesn't perform type checking or restructuring of data just like other languages can do like C# and Java. The typecasting comes with runtime support whereas type assertion has no impact on runtime. However, type assertions are used purely by the compiler and provide hints to the compiler on how we want our code to be analyzed.
Example
To know more click here.
The as is the additional syntax for Type assertion in TypeScript. The reason for introducing the as-syntax is that the original syntax (
Example
When using TypeScript with JSX, only as-style assertions are allowed.
JSX is NOTHING BUT Javascript with a different extension. Facebook came up with this new extension so that they can distinguish from the XML-like implementation of HTML in JavaScript.
JSX is an embeddable XML-like syntax. It is meant to be transformed into valid JavaScript. JSX came to popularity with the React framework. TypeScript supports embedding, type checking, and compiling JSX directly into JavaScript.
To use JSX, we must do two things.
The rest parameter is used to pass zero or more values to a function. It is declared by prefixing the three dot characters ('...')before the parameter. It allows the functions to have a variable number of arguments without using the arguments object. It is very useful where we have an undetermined number of parameters.
Rules to follow in rest parameter:
To know more click here.
Enums or enumerations are a TypeScipt data type that allow us to define a set of named constants. Using enums can make it easier to document intent, or create a set of distinct cases. It is a collection of related values that can be numeric or string values.
Example
Non-Relative | Relative |
---|---|
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"; import { Component } from "@angular/core"; | Relative imports can be used for our own modules that are guaranteed to maintain their relative location at runtime. A relative import is starts with /, ./ or ../. Example: import Entry from "./components/Entry"; import {DefaultHeaders} from "../constants/http"; |
An anonymous function is a function that was declared without any named identifier. These functions are dynamically declared at runtime. Anonymous functions can accept inputs and return outputs, just as standard functions do. An anonymous function is usually not accessible after its initial creation.
Example
Declaration merging is the process followed by the compiler to merge two or more separate declarations. The declaration declared with the same name into a single definition. This merged definition has the features of both of the original declarations.
The simplest, and perhaps most common, type of declaration merging is interface merging. At the most basic level, the merge mechanically joins the members of both declarations into a single interface with the same name.
Example
The three interfaces will merge to create a single declaration as so:
If subclass (child class) has the same method as declared in the parent class, it is known as method overriding. In other words, redefined the base class methods in the derived class or child class.
Rules for Method Overriding
Example
ES6 version of TypeScript provides shorthand syntax for defining the anonymous function, i.e., for function expressions. These arrow functions are also called Lambda functions. A lambda function is a function without a name. Arrow function omits the function keyword.
Example
In the above, the ?=>? is a lambda operator and (a + b) is the body of the function and (a: number, b: number) are inline parameters.
To know more click here.
Fri, 16 Jun 2023
Fri, 16 Jun 2023
Fri, 16 Jun 2023
Write a public review