Top frequently asked Typescript Interview Questions (2021) | TechGeekNxt >>


Top Essential Typescript Interview Questions and Answers


TypeScript is a JavaScript super-set developed by Microsoft, which is strongly typed.

typescript

TypeScript has the best "JavaScript(ES6)" and "Modern Language features (Annotation, Inerfaces, Gernerics)" together which provides similar syntex and functionality like other middle layer languages (like Java, C #). These make it easy for Full Stack Developers to implement. TypeScript is gaining popularity very quickly, and the user community is getting bigger every day.

Google has recently announced that it will start using Typescript internally alongside Java, so Full stack development in Typescript using Node as a runtime will likely become mainstream in the next few years.

In this post, questions from Typescript Interviews will be answered for Experienced and Freshers. We're trying to share our experience and learn how to help you make progress in your career.

  1. What is TypeScript? What are the Benefits of using TypeScript ?
  2. What are the object-oriented terms supported by TypeScript ?
  3. TypeScript vs JavaScript ?
  4. What are the advantages of using Typescript?
  5. What are the different built-in data types supported by TypeScript ?
  6. What are Interfaces in TypeScript ?
  7. What are Classes in TypeScript? List out some of the features. ?
  8. What is tsconfig.json file ?
  9. What are Generics in TypeScript ?
  10. What are TypeScript collections ?
  11. Explain Enum in TypeScript.
  12. What is Lambda/Arrow function ?
  13. Does TypeScript supports function overloading ?
  14. What are the interfaces in Typescript ?
  15. What can we convert string to number using Typescript?
  16. What is a '.map' file, and why/how can you use it ?
  17. What does the 'Record' type do?
  18. Can you explain what are Rest parameters and its rules to declare Rest parameters?
  19. Explain how we can use a class outside a module where it was defined?
  20. What is "as" syntax used in TypeScript?
  21. What exactly is contextual typing?
  22. What exactly is JSX? Is it possible to use JSX in TypeScript?
  23. What JSX modes does TypeScript support?

Q: Why is TypeScript?
Ans:

TypeScript is a superset of JavaScript. Its emphasis on strong typing and advanced language constructs help us write client and server-side code with fewer errors.

TypeScript is cross-platform, open source, and compiles to JavaScript that is compatible with every major browser and popular JavaScript framework. Some of the major concepts are functions, interfaces, classes, modules and namespaces, and generics

The JavaScript language has a handful of types like string, number, and Boolean, but TypeScript lets you define your own types in a very object-oriented manner, and the compiler will then check your code against those types and alert you to problems long before it gets to a production environment. I happen to believe that the addition of types also enables faster development.

If you're using a TypeScript-aware editor (VSCode), it becomes a lot easier to examine the properties and methods available in custom types, and navigate around your project based on the symbols declared in your code.

Q: TypeScript vs JavaScript?
Ans:

TypeScript
JavaScript
TypeScript is an Object-Oriented programming concept like classes, interfaces, inheritance, generics, etc. JavaScript is a Scripting language
It has a feature known as Static typing It does not have static typing
TypeScript gives support for modules, generics, ES6 JavaScript does not support modules, generics, ES6
It supports optional parameter function It does not support optional parameter function
It compiles the code and highlighted errors during the development time. It is interpreted language that's why it highlighted the errors at runtime.
In this, number, string are the interface. In this, number, string are the objects
It was developed by Anders Hejlsberg in 2012. It was developed by Netscape in 1995.

Q: What are the advantages of using Typescript?
Ans:

  • TypeScript is fast, simple, and most importantly, easy to learn.
  • TypeScript supports development of object-oriented code features such as classes, interfaces, inheritance, generics, etc even with minimal knowledge.
  • TypeScript offers an API for DOM manipulation.
  • Typescript has very good IDE support, as autocompletion, type checking, and source documentation. Which Help developers save a ton of valuable time.
  • TypeScript can be used for both server-side and client-side development alike.
  • TypeScript comes with types that make code easier to read and void major errors. It is better for the compiler to catch errors than to have things fail at runtime
  • TypeScript are one of the best forms of documentation you can have. The function signature is a theorem and the function body is the proof
  • TypeScript also has the concept of the namespace by Module defining, which makes it reusable and allow lazy loading.
  • TypeScript supports the latest JavaScript features including ECMAScript 2015 and also gives all the benefits of ES6 plus more productivity.

Q: What are the different types supported by TypeScript ?
Ans:

String: A string is a series of characters that are stored as UTF-16 Unicode code
Number: It reflects the values of the number form. The numbers are stored as floating-point values in TypeScript
Boolean: This can have values as true or false
Array: This can be a list of numbers together
Tuple: This data type allows users to create an array where the fixed number type elements are known but not the same.
Enum: This allows creating a user-defined data type.
Undefined: The Undefined type denotes all uninitialized variables.
Void: A void is the return type of the functions that do not return any type of value.
Null: Null represents a variable whose value is undefined. It is not possible to directly reference the null type value itself.
Any: It can be implemented to ensure data value to declare said values.
Never: It represents the data type of values that never occur.

Q: What are TypeScript collections ?
Ans:

Like other programing languages Typescript also has support for Collection, like Map, Set etc.

To know more about Typescript Collections, click here

Checkout our related posts :

Q: What are Generics in TypeScript ?
Ans:

Generics are a feature of TypeScript, which allows you to take advantage of that type safety while creating code you can reuse throughout your apps.
  • Reusable type-safe code that works with multiple types
  • May be functions, interfaces, or classes
  • Code that accepts type parameters for each instance or invocation
interface DataStructure<T> {
  push(newItem: T): void;
  pop(): T;
}

class Stack<T> implements DataStructure<T> {
  
  items: Array<T> = [];
  
  push(newItem: T): void {
    this.items.push(newItem);
  }
  
  pop(): T {
    return this.items.pop();
  }

  peek(): T {
    return this.items[this.items.length - 1];
  }
}

let numberStack = new Stack<number>();

numberStack.push(10);
numberStack.push(20);
numberStack.push(30);

console.log(numberStack.pop()); // 30
console.log(numberStack.peek()); // 20
console.log(numberStack.pop()); // 20
console.log(numberStack.pop()); // 10

Q: Explain Enum in TypeScript. ?
Ans:

Enums are a data form TypeScipt that enables us to define a set of named constants. Enums may facilitate recording purposes or setting up a number of different cases. It is a collection of related values, numeric or string values.
enum Size {
  Big,  
  Medium  
  Small  
}  
console.log(Size.Medium); // Output: 1  
//We can also access an enum value by it's number value.  
console.log(Size[1]); // Output: Medium  

Q: What is tsconfig.json file ?
Ans:

The file tsconfig.json is a JSON-based format. We may define multiple options to display the compiler how to create the current project in the tsconfig.json file. The presence of the file tsconfig.json in a directory indicates that the folder is the root of the project TypeScript. The sample tsconfig.json is described below.
{
   "compilerOptions": {
      "declaration": true,
      "emitDecoratorMetadata": false,
      "experimentalDecorators": false,
      "module": "none",
      "moduleResolution": "node"
      "removeComments": true,
      "sourceMap": true  
   },  
   "files": [
      "main.ts",  
      "othermodule.ts"  
    ]  
}  

Q: What is Lambda/Arrow function ?
Ans:

ES6 TypeScript version provides a shorthand syntax, i.e. for function expressions, to define the anonymous function. The functions of this arrow are known as Lambda functions. A lambda function is a function without a name. The function arrow omits the keyword function.
let sum = (a: number, b: number): number => {
            return a + b;
}    
console.log(sum(10, 20)); //returns 30    
We = > operator means arrow / Lambda operator in the example as mentioned previously. The parameters a and b here are, and the function body (a + b) is considered.

Q: Does TypeScript supports function overloading ?
Ans:

Yes, TypeScript support function overloading. However, the execution is strange. Only one function with multiple signatures can be implemented when we perform overload in TypeScript.
//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;
}    
The first two lines are the overload declaration function in this example. It is overloaded by two. The former has a string parameter while the former has a type number parameter. The third function contains the actual execution and has a type parameter. Any type of data can take data of any kind. The execution then checks the parameter type and executes another code based on the supplier parameter type.

Q: What are the interfaces in Typescript ?
Ans:

The interface defines the syntax for any variable or entity. Interfaces define properties, methods, and events. Only the members are declared here. Interfaces are useful in defining different members and help to define the structure of the drifting classes. Interfaces can be declared using the keyword of the interface.
interface Employee {
   name: string,
   dob: date,
   address: string,
   getDepartment: ()=>string
}

Q: What can we convert string to number using Typescript?
Ans:

In Typescript this can be achieved in 4 ways :
// Using parseInt
parseInt(x)

// Using parseFloat
parseFloat(x)

// Using Unary like +,* operator
let a = "1";
let b: number = +a;

// Using Number
Number('123')

Q: What is a '.map' file, and why/how can you use it ?
Ans:

A map file is a source map file that can be used for debugging. It can be generated by setting the option of the sourceMap compiler to true in tsconfig.json

{
  "compilerOptions": {
    ...
    "sourceMap": true,
  }
}

Q: What does the 'Record' type do?
Ans:

It allows you to create a typed "map".

let Employee = Record<string, number> = {};
Employee.age = 35;

Q: Can you explain what are Rest parameters and its rules to declare Rest parameters?
Ans:

A rest parameter is used to pass a function to zero or more values. By prefixing the three-dot characters ('...') before the parameter, it is declared. It makes it possible for functions to have a variable number of arguments without using the object argument. Where we have an undetermined number of parameters, it is very useful.

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.
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(1, 2);
let result2 = sum(1,2,4,6);

Q: Explain how we can use a class outside a module where it was defined?
Ans:

Here is an example how we can use class outside module with export keyword :
module Admin {
  // use the export keyword in TypeScript to access the class outside
  export class Employee {
    constructor(name: string, email: string) { }
  }
  let alex = new Employee('alex', 'alex@gmail.com');
}

// The Admin variable will allow to accessed the Employee class outside the module with the help of export keyword in TypeScript
let nick = new Admin.Employee('nick', 'nick@yahoo.com');

Q: What is "as" syntax used in TypeScript?
Ans:

The "as" is used for Type assertion in TypeScript. The as-syntax was implemented because the original syntax (type>) clashed with JSX.

Q: What exactly is contextual typing?
Ans:

If you have types on one side of the equation but not the other, the TypeScript compiler will find out the form. For instance, we can rewrite the preceding example function as follows:

let sum: (firstNumber: number, secondNumber: number) => number =
                                        function(x, y) { return x + y; };

We should omit the typings on the right side of the equal since TypeScript can work it out automatically. This decreases the amount of work needed to keep our code typed.

Q: What exactly is JSX? Is it possible to use JSX in TypeScript?
Ans:

JSX is an XML-like syntax that can be embedded. It is supposed to be translated into valid JavaScript.

  • With the React system, JSX gained popularity. TypeScript allows you to embed, type search, and compile JSX directly into JavaScript.
  • To use JSX in our file, we must name it with .tsx extension and allow the jsx feature.

Q: What JSX modes does TypeScript support?
Ans:

There are three JSX modes included with TypeScript: preserve, respond, and react-native.

  • Preserve mode :The preserve mode holds the JSX as part of the output, ready to be consumed by a subsequent transform stage (e.g. Babel). The output would also have an extension of the.jsx format.
  • React mode :The react mode will emit React.createElement, which does not need any JSX transformation before use and has a.js file extension.
  • React-native mode :The react-native mode is similar to preserve mode in that it holds all JSX but outputs a.js file.


Recommendation for Top Popular Post :


Adblocker detected! Please consider whitelist or disable ad-blocker.

We have found that you use AdBlock Plus or any other adblocking software to prevent a full loading of the website.

We've got no banner, Flash, animation, disgusting sound, or pop-up ad. These obnoxious types of advertising are not implemented!

To operate the website, we require funding and nearly everything is from our internet advertising.


Please add techgeeknext.com to your ad blocking whitelist or disable your adblocking software.

×