Typescript Interview Questions: Part 2

Typescript Interview Questions: Part 2
Typescript Interview Questions: Part 2

Introduction

TypeScript is a programming language developed and maintained by Microsoft. The inadequacies of JavaScript in the development of large-scale applications led to the creation of TypeScript. It’s a strict superset of JavaScript with the addition of optional static typing.

One interesting fact about Typescript is, the typeScript compiler is itself written in the TypeScript programming language.

This blog has various typescript interview questions and answers for experienced candidates as well as for freshers.This series includes 50 of the most frequently asked interview questions, divided over two blogs. 

This blog consists of the last 25 questions. It’s recommended to visit TypeScript interview questions | Part 1 before getting started with this article.

We’ve also included some lesser-known facts about JavaScript and TypeScript at the end of this article as a treat for you to complete reading this series. 

Without further ado, let’s get started.

Typescript Interview Questions

  1. What are decorators in TypeScript?

Answer: A Decorator is a type of declaration that can be used with classes, methods, accessors, properties, and parameters. Decorators are functions that begin with the @expression symbol and evaluate to a function that is called at runtime with the passed information about the decorated declaration.

The objective of TypeScript Decorators is to add annotations and metadata to existing code in a declarative manner. To enable experimental decorator support, either on the command line or in our tsconfig.json, activate the experimentalDecorators compiler option:

Command Line

$tsc --target ES5 --experimentalDecorators

tsconfig.json

{
"compilerOptions": 
     {
          "target": "ES5",
          "experimentalDecorators": true
     }
}
  1. What are Mixins in TypeScript?

Answer: Mixins create components and then merge simpler partial merges in Javascript.

Instead of class A extending class B to gain its functionality, function B accepts class A and returns a new class. Function B is a mixin in this case.

blog banner 1
  1. What type of support does TypeScript provide for optional parameters in functions?

Answer: If you try to invoke a function without giving the precise number and types of parameters as declared in its function signature, the TypeScript compiler produces an error. 

Optional parameters, denoted by a question mark symbol (‘?’), can be used to solve this problem. It indicates that parameters that may or may not receive a value should be preceded by a ‘?’ to indicate that they are optional.

For example: In the example below, argument1 is always necessary, whereas argument2 is optional.

function OptionalDemo(argument1: number, argument2? :number) {}
  1. In TypeScript, what is the Scope variable?

Answer: A scope is a collection of objects, variables, and functions, and a JavaScript variable can have both a global and local scope.

We can declare a variable in two scopes.

  • Local Scope Variable – It’s a type of function object that is used within functions.
  • Global Scope Variable – This window object can be used in both inside and outside of functions.
  1. What is the optimal way to debug a TypeScript file?

Answer: A .js source map file is required to debug any TypeScript file. To generate a source map file, you must compile the .ts file using the sourcemap flag.

Example: 

$ tsc -sourcemap file.ts

This will create a file.js and file.js.map. And the last line of file.js would be a reference to the source map file.

//# sourceMappingURL=file1.js.map
  1. What exactly is the TypeScript Definition Manager, and why do we require it?

Answer: The TypeScript Definition Manager (TSD) is a package manager that allows us to search for and install definition files directly from the DefinitelyTyped repository maintained by the community.

For example: 

To use some jQuery code in .ts file:

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

When you try to compile it with tsc, you’ll get the following error: Cannot find the name “$.” As a result, you must tell the TypeScript compiler that “$” belongs to jQuery. TSD is used to do this. You may include the jQuery Type Definition file in our.ts file by downloading it.

  1. What is the procedure for including a Type Definition File in TypeScript?

Answer: The following are the steps involved in incorporating the Type Definition File:

S.NoInstructionsSyntax
1First, you have to install TSD.$ npm install tsd -g
2Next, under the TypeScript directory, execute $ tsd init to create a new TypeScript project.$ tsd init
3Then install the jQuery definition file.tsd query jquery –action install
4The command above will download and create a new directory that contains the jQuery definition file that ends in “.d.ts.” Update the TypeScript file to point to the jQuery definition to include the definition file./// <reference path=”typings/jquery/jquery.d.ts” />$(document).ready(function() { //To Do});
5Finally, recompile the code. This time, the js file will be generated correctly. As a result, TSD is required to obtain the type definition file for the framework.
  1. What is the purpose of the TypeScript Declare keyword?

Answer: TypeScript declaration files are not present in JavaScript libraries or frameworks. However, we can use the “declare” keyword in a TypeScript file without causing a compilation issue. Declare is used in ambient declarations and procedures to define a variable that may or may not exist elsewhere.

We can use the following code to include the library in our TypeScript code:

declare var myLibrary; 

The TypeScript runtime will assign any type to the myLibrary variable.

  1. What is TypeScript’s Default Parameters Function?

Answer: By default, values can be assigned to function parameters. It is not possible to designate a parameter as both optional and default at the same time.

Example:

let rebate = function (price: number, rate: number = 0.40) 
{
return price * rate;
}
rebate(500); // Result - 200
rebate(500, 0.45); // Result - 225

In the example above, the rate is a default argument in the rebate function as a number. If we specify a value in the rebate rate param, it will be used. If we don’t provide any value the default value of 0.40 will be used.

  1. What is the tsconfig.json file in TypeScript?

Answer: The tsconfig.json file is a JSON-formatted document. We can set multiple options in the tsconfig.json file to inform the compiler how to compile the current project. The tsconfig.json file in a directory indicates the TypeScript project’s root directory.

  1. What are TypeScript Generics?

Answer: TypeScript Generics is a tool for generating reusable components in TypeScript. Instead of working with a single data type, it can develop components that operate with various data types. 

Additionally, it ensures type safety without sacrificing performance or efficiency. Generic classes, functions, methods, and interfaces are all possible with generics.

A type parameter in generics is written between the open (<) and close (>) brackets, resulting in highly typed collections. It makes use of a specific type variable called <T> to represent types.

For example: 

function identity<T>(arg: T): T 
{
return arg;
}
let output1 = identity<string>("CodingNinja");
let output2 = identity<number>( 117 );
console.log(output1);
console.log(output2);
  1. What is JSX in TypeScript?

Answer: JSX is an XML-like syntax that can be embedded and converted into valid JavaScript. With the React framework, JSX gained popularity. TypeScript allows you to embed, type-check, and compile JSX into JavaScript.

To use JSX in our file, we must give it a .tsx extension and enable the jsx option.

  1. What’s the difference between a type statement and an interface statement?

Answer: The fundamental difference between a type statement and an interface statement is as follows:

InterfaceType
A named object type is introduced via an interface declaration.A type alias declaration gives any type, including primitive, union, and intersection types, a name.
It can be named in a clause that extends or implements.An object type literal’s type alias cannot be mentioned in an extends or implements clause.
Interfaces give a new name that is utilised all over the place.They don’t create any new name
Multiple merged declarations are possible.Multiple merged declarations are not allowed.
  1. What types of JSX modes does TypeScript support?

Answer: TypeScript supports three JSX modes. 


  • The preserve option maintains the JSX in the output so that another transform step can consume it. The output will also have a .jsx extension. 
  • The react mode emits React.createElement, which does not require any JSX transformation before use and has a.js file extension.
  • The preserve mode is comparable to the react-native mode, but the output has a.js file extension instead of JSX.
  1. What are TypeScript Ambients, and when should we utilise them?

Answer: Ambient declarations inform the compiler about any other source code that may exist. If we try to use these source codes at runtime and they do not exist, the program will crash without notice.

Ambient declarations files are similar to docs files. They include information about the environment. If the source changes, the docs must be changed, and compiler issues will occur if the ambient declaration file is not updated. It also allows us to use current popular JavaScript libraries like jquery, angular js, node js, and others safely and efficiently.

  1. What is a TypeScript Map file, and what does it do?

Answer: The TypeScript Map file is a source map file that contains information about the files we started with. The .map files are the source map files that allow tools to map between output JavaScript code and the TypeScript source files that produced it. Debuggers can also consume these files, allowing us to debug the TypeScript file rather than the JavaScript file.

  1. What are Rest parameters in TypeScript?

Answer: The rest parameter is used to pass a function with zero or more values. It is declared by prefixing the argument with the three-dot letters (‘…’). It enables functions to take a variable number of arguments without requiring the use of the arguments object. It comes in handy when there are an unknown amount of parameters.

  1. What are Type Assertions in TypeScript?

Answer: In other languages, such as C# and Java, type assertion functions similarly to typecasting, but it does not conduct type checking or data rearrangement. Typecasting includes runtime support, whereas type assertion does not affect the runtime. On the other hand, type assertions are used solely by the compiler and provide instructions on how we want our code to be analysed.

  1. What rules apply to declaring Rest parameters? Give a specific example.

Answer: The following are the rules to follow while using the rest parameter:

  • A function can only have one rest parameter.
  • It has to be of the array type.
  • It has to be the last parameter in the list of parameters.
  1. What is “as” syntax in TypeScript?

Answer: In TypeScript, the “as” is a different syntax for Type assertion. The as-syntax was introduced since the prior syntax was incompatible with JSX.

  1. What are enums in TypeScript?

Answer: Enums, often known as enumerations, are a data type in TypeScript that allows us to define a collection of named constants. It’s easy to document purpose or construct a set of exceptional cases when you use enums. It’s a grouping of similar values, which might be numeric or textual.

Example:

enum GenderDemo 
{
Male,
Female
Other
}
console.log(GenderDemo.Male); // Output: 0
console.log(GenderDemo[1]); // Output: Female
  1. Explain the differences between relative and non-relative module imports.

Answer: 

  • Non-Relative

A non-relative import can be resolved via path mapping or relative to baseUrl. In other words, when importing any of our external dependencies, we use non-relative routes.

Example:

import * as $ from “jquery”;

import { Component } from “@angular/core”;

  • Relative 

Relative imports can be used for individual modules to ensure that their relative location is maintained at runtime. A relative import begins with the characters /, ./, or ../.

Example: 

import Entry from “./components/Entry”;

import {DefaultHeaders} from “../constants/http”;

  1. What is the definition of an anonymous function?

Answer: A function that is declared without a named identifier is known as an anonymous function. At runtime, these functions are dynamically declared. Anonymous functions, like normal functions, can accept inputs and return outputs. It usually isn’t accessible after it’s been created.

Example: 

let Add = function(x: number, y: number): number 

return x+y; 
}; 
console.log(Add())
  1. In TypeScript, what is method overriding?

Answer: Method overriding occurs when a subclass or child class has the same method declared in the parent class. Essentially, the derived class or child class redefines the base class methods.

Method Overriding Rules:

  • The method must be named the same as the parent class’s method.
  • The parameter must be the same as in the parent class.
  • An IS-A relationship or inheritance must exist.
  1. What is the Lambda/Arrow function in TypeScript?

Answer: For defining anonymous functions, i.e. function expressions, the ES6 version of TypeScript provides a shortcut syntax. Lambda functions are another name for these arrow functions. A lambda function has no name. The arrow function, on the other hand, does not use the function keyword.

Example:

let sum = (x: number, y: number): number => 

return x + y; 

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

In this example, the ?=>? is a lambda operator and (x + y) is the body of the function and (x: number, y: number) are inline parameters.

Some lesser-known facts about JavaScript and TypeScript

JavaScript: 

  1. The NaN(Not a number) property of objects is a number. Also, NaN is not equal to itself as well.
console.log(typeof(NaN))

[LOG]: "number"
  1. The null value denotes the intended absence of any object value. Here’s a fact, a null is an object itself.
console.log(typeof(null))

[LOG]: "object"
  1. The Math.max() function is smaller than Math.min() in JavaScript.
console.log(Math.min()>Math.max());

[LOG]: true

The reason is if no argument is passed in Math.min(), it returns infinity. And if no argument is passed in Math.max(), it returns minus infinity.

console.log(Math.min());

[LOG]: Infinity
 
console.log(Math.max());

[LOG]: -Infinity
  1. Functions can execute themselves in JavaScript by using () just after the declaration.
(function()  { console.log('Hey, Ninja! I am self executing');  })();

[LOG]: "Hey, Ninja! I am self executing"
  1. JavaScript does not have an integer data type. All of the numbers in JavaScript are of the number type. In reality, it saves a float value for an int number in memory.

Let’s see some facts about TypeScript now.

TypeScript:

  1. TypeScript is more than simply a scripting language; it includes modern language features, such as generics, enums, OOP, interfaces, types, decorators, and modules.
  1. We can compile TypeScript into whichever version of JavaScript we want. We can select any version of JavaScript via the –target compiler option.
  1. TypeScript is a free and open-source programming language that is being developed on GitHub. Any JavaScript server can use the TypeScript compiler, which is written in TypeScript.
  1. Because TypeScript is based on C #, it’s simple for developers who have previously worked with C # or Java to transition to Frontend development.
  1. TypeScript Enabled JavaScript to Scale. Early versions of JavaScript lacked the features needed to construct enterprise-level apps. TypeScript provided those features, making complicated application design and development easier.

Hopefully, you learned something new or showed an improved understanding of what’s new with JavaScript and TypeScript.

Javascript is one of the most powerful and widely used programming languages of the web. Check out  Top 100 Javascript Interview Questions to help you crack your interviews and get your dream job.

Key Takeaways

We’ve reached the conclusion of our TypeScript interview questions blog. This TypeScript package includes 50 of the most frequently asked interview questions, divided over two blogs. It’s recommended to visit Part 1 before getting started with this typescript interview questions | Part 2.

If you are going to appear for an interview related to TypeScript, this series has it all. These two blogs give a glance at all the basic and essential concepts. Answers to the questions are precise and to the point. 

We hope you find these TypeScript Interview questions helpful in your upcoming interviews.

Happy Learning!

By: Vaishnavi Pandey