preloader
Typescript Interview Questions

50+ TypeScript Interview Questions and Answers for Job Interview

author image

Appearing for a technical job interview in the IT sector then you need to prepare from TypeScript Interview Questions and Answers. If your core topic of Interview is TypeScript then you really need to prepare the given TypeScript interview questions properly and if you are preparing for other languages like Javascript etc then also you need to go through the typescript questions as they are interconnected so you might be asked questions related to typescript so prepare from here.

About TypeScript: It is an open-source language that is a static or strongly typed superset of JavaScript developed by Anders Hejlsberg at Microsoft. It is made to compile with Javascript and runs on any browser, host, and OS. In simple terms, all valid JavaScript code can be called TypeScript code. It has great features like IntelliSense, code completion, safe refactorings, etc.

TypeScript Interview Questions

1. Define Typescript?

2. What are some advantages of TypeScript?

3. Tell us some features of Typescript?

4. Benefits of using Typescript?

5. Disadvantages of TypeScript?

6. Explain various components of TypeScript?

7. Who developed Typescript?

8. How do we install and use TypeScript

9. List some primitive data types in Typescript.

10. Explain variables in Typescript and how to create them?

11. How to compile a Typescript file?

12. How to combine multiple TypeScript .ts files into a single Javascript .js file?

13. Tell the latest version of Typescript?

14. How do .ts automatically compile with real-time changes?

15. Explain interfaces and their reference to Typescript.

16. Explain classes in Typescript?

17. Is Native Javascript supports modules?

18. Name the object-oriented terms that are supported by TypeScript?

19. In TypeScript How to Call Base Class Constructor from Child Class?

20. What are the ways to implement inheritance in TypeScript?

21. Explain Modules in Typescript?

22. Name features of a class in Typescript?

23. Explain namespace in Typescript and How to declare it?

24. Describe Decorators in Typescript?

25. Explain Mixins?

26. Tell the default set visibility for properties/methods?

27. How does TypeScript support optional parameters in function?

28. Is function overloading supported by TypeScript?

29. How to debug any TypeScript file?

30. Explain TypeScript Definition Manager and why do we need it?

31. What is TypeScript Declare Keyword?

32. How to create a TypeScript definition file from the .ts file?

33. What is the tsconfig.json file?

34. Explain generics in TypeScript?

35. Name all object-oriented principles that TypeScript supports?

36. Tell the way to check null and undefined in TypeScript?

37. How to use TypeScript on the backend?

38. Explain how an interface is different from type statements?

39. Explain Ambients and their use in TypeScripts?

40. Explain TypeScript Map file?

41. Describe Type assertions in TypeScript?

42. Explain "as" syntax in TypeScript?

43. Explain JSX and its use in TypeScript?type

44. Describe Rest parameters?

45. What do you understand by Enum in TypeScript?

46. Explain parameter destructuring?

47. Explain anonymous function?

48. Explain Declaration Merging?

49. Explain the overriding method in TypeScript?

50. Explain Lambda/Arrow function?


Learn More Interview Questions Here:


TypeScript Interview Questions and Answers

1. Define Typescript?

It is a programming language that is free and available open-source that is developed and maintained by Microsoft. It is a superset of JavaScript which is strongly typed that compiles with plain JavaScript. It is a programming language used for application-scale development by Javascript. It is quite easy to understand and learn and used with C#, Java languages. It can be run on any browser, Host, and OS. TypeScript is not directly working on the browser but does require a compiler to work and generate in JavaScript file. It is the ES6 version of JavaScript.

2. What are some advantages of TypeScript?

  • It is easy to learn, fast and simple.
  • It supports classes, interfaces, etc. object-oriented programming features.
  • It uses an error-checking feature at the time of compilation. It highlighted the errors before running the script.
  • It is a superset of JavaScript and supports all JavaScript libraries.
  • It allows reusability with the usage of inheritance.
  • The latest JavaScript features of ECMAScript 2015 is also supported by TypeScript
  • It increases productivity and gives the benefits of ES6.
  • It supports various functions and features, static typing, Strongly type, Modules, etc.

3. Tell us some features of Typescript?

  • Object-Oriented language
  • Support Javascript Libraries
  • JavaScript is TypeScript
  • Typescript is portable
  • DOM Manipulation
  • TypeScript is just Javascript

4. Benefits of using Typescript?

  • It easily adds variables, functions, properties, etc.
  • Typescript compiles with JavaScript and runs on all browsers.
  • It also highlights errors at the time of compiling during development.
  • TypeScript supports static typing or strong typing.
  • It structure codes.
  • Class-based object-oriented programming is used in TypeScript.
  • It provides tool support with IntelliSense.

5. Disadvantages of TypeScript?

  • Its code compilation time is longer.
  • It doesn’t support abstract classes.
  • To run a TypeScript application in any browser, a compiler, and its setup is required to convert TypeScript into JavaScript.
  • Developers are using JavaScript for years and TypeScript does not bring anything new.
  • To use a third-party library, the definition file is required and all the third-party libraries don’t have it.

6. Explain various components of TypeScript?

There are majorly three components of typescripts use which are:

Language: It contains elements like keywords, type annotations, new syntax, etc., and permits the developer to write TypeScript.

Compiler: It is an open-source, cross-platform which is written in TypeScript. It converts the code written in TypeScript to JavaScript code. It executes the parsing, type checking of TypeScript code to JavaScript code. It concatenates different files to one file and generates source maps.

Language Service: It provides information due to which editors and other tools can give better assistance features like IntelliSense and automated refactoring.

7. Who developed Typescript?

Anders Hejlsberg developed the typescript, he is among the core members of C# language developers. It was first released on October 1st, 2012 with labeled version 0.8. After that TypeScript is developed and sustained by Microsoft under the Apache 2 license. It was generally made for the development of a heavy and large application.

8. How do we install and use TypeScript

To install and use TypeScript you will be required node via npm (the Node.js package manager). Ensure that the npm is properly installed, then run the command to install TypeScript.

$ npm install -g typescript

The command line code “tsc” is used to install and compile our Typescript code. Check the version of TypeScript before installing.

Follow the steps to install TypeScript:

  • Download and run the .msi installer for the node.
  • Place command “node -v” to check whether the installation is successful or not.
  • Enter the given command in the terminal window to install Typescript

9. List some primitive data types in Typescript.

The primitive data types are also known as built-in data types in Typescript.

Number type: It represents the numerical type values. All the numbers are saved in floating-point values.

Syntax: let identifier: number = value;

String type: It displays Unicode UTF-16 code (a stored sequence of characters). To use string literals in scripts we need to enclose them in single or double quotation marks.

Syntax: let identifier: string = " “;

Boolean type: It displays a logical value. Boolean type gives the result only in true or false.

Syntax: let identifier: bool = Boolean value;

Null type: Null shows a variable whose value is not defined and because of this it is impossible to directly mention the null type value itself. It is not quite useful as we can only assign an undefined or null value to it.

Syntax: let num: number = null;

Undefined type: It denotes all uninitialized variables so this is why it is not useful because only an undefined value can be assigned to it. This type of primitive date type is the sub-type of all the types.

Syntax: let num: number = undefined;

Void type: It is the return type function that doesn’t return any type of value. It is only used where no datatype is available.

Syntax: let unusable: void = undefined;

10. Explain variables in Typescript and how to create them?

A variable is basically a storage location that saves value/information used by programs. Variables act like a container for value in a program. The var keyword is used to declare a variable. At the time of declaring a variable, some rules need to be followed-

  • The name should be limited to the alphabet or numeric.
  • The variable name cannot be started with a digit.
  • The name must not have any spaces and special character with exception of underscore (_) and the dollar($) sign.

Four ways to declare a variable:

  1. If you are declaring type and value in a single statement. Syntax: var [identifier] : [type-annotation] = value;
  2. If you are declaring type without value. Syntax: var [identifier] : [type-annotation];
  3. If you are declaring its value without type. Syntax: var [identifier] = value;
  4. If you are declaring without value and type. Syntax: var [identifier];

11. How to compile a Typescript file?

Follow this command used to compile a Typescript file into JavaScript.

$ tsc

For example, to compile “jobinterviewninjas.ts.”

$ tsc jobinterviewninjas.ts

The result would be jobinterviewninjas.js.

12. How to combine multiple TypeScript .ts files into a single Javascript .js file?

You need to use –outFILE [OutputJSFileName] compiling option.

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

The given command will compile all files that are file1, file2, and file3 “.ts” file, and the output file is stored into one “comman.js” file. In this case, the .js file name is mentioned in the command.

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

In case there is no name of the .js file mentioned then, file2.ts and file3.ts will be compiled, and the final file will be placed in file1.ts. So now the newly generated file1.ts contains JavaScript code.

13. Tell the latest version of Typescript?

The latest version of TypeScript is 3.2 which was made available on September 30, 2018. It compiles simple JavaScript code and runs on any browser that supports the ECMAScript 2015 framework. It uses the latest and evolving JavaScript features.

14. How do .ts automatically compile with real-time changes?

By using the –watch compiler option you can automatically compile with real-time changes in the .ts file.

tsc –watch file1.ts

The given command compiles file1.ts in file1.js and automatically watches for the file changes. If any changes are found, the file will compile itself again. Just make sure that the command is not closed promptly on running with –watch option.

15. Explain interfaces and their reference to Typescript.

In Interface a structure that performs as a contract in an application. It explains through syntax which classes to follow, which simply states that a class that implements an interface is sure to implement all its members. It can’t be instantiated but refers to the class object that implements it. The compiler uses an interface for type-checking (also called “duck typing” or “structural subtyping”) whether the object structure is specified or not.

Syntax:

interface interface_name {

// variables’ declaration

// methods’ declaration

}

The interface only states the methods and fields and cannot be used to build or develop anything. It does not require any conversion to JavaScript for execution and has zero runtime JavaScript impact. So, the interface’s core purpose is to help in the development stage.

16. Explain classes in Typescript?

It is a type of Object-Oriented JS language that supports OOPs programming features like classes, interfaces, etc. As an example, Java classes are the fundamental units that develop reusable components. Classes are a group of objects which share common properties. It is basically a template or blueprint which is used for creating objects. To declare it use the “class” keyword.

Example:

class Student {

studCode: number;

studName: string;

constructor(code: number, name: string) {

this.studName = name;

this.studCode = code;

}

getGrade() : string {

return “A+” ;

}

}

17. Is Native Javascript supports modules?

Presently, Native JavaScript does not support modules. You require an external like CommonJS to create and work with modules in Javascript.

18. Name the object-oriented terms that are supported by TypeScript?

  • Modules
  • Classes
  • Interfaces
  • Inheritance
  • Data Types
  • Member functions

19. In TypeScript How to Call Base Class Constructor from Child Class?

Use a super() function to call parent or base class constructor from Child Class.

20. What are the ways to implement inheritance in TypeScript?

It is a mechanism that gets the properties and behaviors of one class from another class. It can create a new class from an already existing one this is an aspect of OOPs programming languages. The class that gives away the member is the base class, and the class that takes away those members is the derived class. For 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

21. Explain Modules in Typescript?

It is used to create a group of related variables, classes, interfaces, and functions, etc. It is performed within their scope. These variables, classes, interfaces, and functions are not accessible outside the module directly. Creating a Module: By using the export keyword you can create a module and can be used in other modules by using the import keyword. module module_name{ class xyz{ export sum(x, y){ return x+y; } } }

22. Name features of a class in Typescript?

  1. Inheritance
  2. Encapsulation
  3. Polymorphism
  4. Abstraction

23. Explain namespace in Typescript and How to declare it?

A namespace also called internal modules is a way used to make a logical group of functionalities. Namespace internally maintains the legacy code of typescript. It captures the features and objects that have some relationships between them. It uses interfaces, classes, functions, and variables to make a group of related functionalities. Syntax for creating namespace namespace <namespace_name> { export interface I1 { } export class c1{ } }

24. Describe Decorators in Typescript?

It is a special declaration that works on methods, classes, property, accessor, or parameter. It simply functions and you just need to add a prefix @expression symbol, where expression must evaluate to a function that will be called at runtime with information about the decorated declaration. TypeScript Decorators add both annotations and metadata to the prevailing code in a declarative way. They are an experimental feature proposed for ES7 and used by some JavaScript frameworks which involve Angular 2. You need to use the experimentalDecorators compiler option to the command line or in tsconfig.json file to enable experimental support for decorators Command Line 1. $tsc --target ES5 --experimentalDecorators tsconfig.json { "compilerOptions": { "target": "ES5", "experimentalDecorators": true } }

25. Explain Mixins?

Mixins are a way of making classes from reusable components by mixing simpler partial classes. The idea behind it is simple, in place of extending class A to class B for functionality, function B takes over to class A and comes with a new class with this added functionality. Function B is a mixin.

26. Tell the default set visibility for properties/methods?

The public is the set default visibility for TypeScript classes’ properties/methods.

27. How does TypeScript support optional parameters in function?

In TypeScript the compiler will show an error if we try to run a function without declaring the exact number and types of parameters in the function signature. To rectify this fault, optional parameters are added by using the question mark sign ('?'). It shows that the parameters which may or may not receive a value can be affixed with a ‘?’ to mark them optional.

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

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

Note: Optional parameters need to follow the required parameters. If you are making arg1 optional and arg2 required, then we need to change the orders

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

}

28. Is function overloading supported by TypeScript?

Yes, TypeScript does support the function overloading. It is a bit odd, so when we execute function overloading in TypeScript, only one function is implemented with multiple signatures. //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 above example explains that the first two lines of code use the function overload declarations which have two overloads. The first signature is a type string parameter whereas the second signature is a type number parameter. The third function has the actual implementation with the parameter of type any data. The implementation then looks for the type of the parameter supplied and performed to a different piece of code based on the supplier parameter type.

29. How to debug any TypeScript file?

To debug a TypeScript file, you do require a .js source map file. So you need to compile the .ts file with the –sourcemap flag to finally get a source map file.

$ tsc -sourcemap file1.ts

The above command will create file1.js and file1.js.map. And the last line mentioned in file1.js would refer to a source map file.

//# sourceMappingURL=file1.js.map

30. Explain TypeScript Definition Manager and why do we need it?

TSD is a package manager which is used to search and install TypeScript definition files directly from the DefinitelyTyped repository.

Let assume to use some jQuery code in our .ts file.

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

Now, if you compile the code using tsc, then it shows a compile-time error: Cannot find the name “$”. So, you notify the TypeScript compiler that “$” belongs to jQuery and for this, TSD is used. You need to download the jQuery Type Definition file and add it to our .ts file. Follow the steps to run:

First, install TSD.

$ npm install tsd -g

In the TypeScript directory, create a new TypeScript project by running:

$ tsd init

Now install the definition file for jQuery.

tsd query jquery –action install

Through this command, you can download and create a new directory that has a jQuery definition file that ends with “.d.ts”. Now, add this definition file by upgrading the TypeScript file to point to the jQuery definition.

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

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

});

Now, try to compile again and the js file will be created without any error. Hence, the requirement of TSD helps us to get a type definition file for the required framework.

31. What is TypeScript Declare Keyword?

It is known to all that JavaScript libraries/frameworks don’t contain TypeScript declaration files, but it is required in TypeScript files with no compilation errors. The declare keyword is utilized for ambient declarations & methods where you need to define a variable that may exist elsewhere.

For example, let assume we already have a library called myLibrary with no TypeScript declaration file and the namespace given to it is myLibrary in the global namespace. If we use that library in our TypeScript code, then we require this code:

declare var myLibrary;

32. How to create a TypeScript definition file from the .ts file?

By using tsc compiler we can generate a TypeScript definition file from any .ts file which makes it reusable.

tsc –declaration file1.ts

33. What is the tsconfig.json file?

This file is in a JSON format, with the help of this file, we can have multiple options to inform the compiler about how to compile the current project. This file directory specifies that the directory is used as a root of a TypeScript project.

{

“compilerOptions”: {

“declaration”: true,

“emitDecoratorMetadata”: false,

“experimentalDecorators”: false,

“module”: “none”,

“moduleResolution”: “node”

“removeComments”: true,

“sourceMap”: true

},

“files”: [

“main.ts”,

“othermodule.ts”

]

}

34. Explain generics in TypeScript?

It is a tool that creates reusable components that can work with a variety of data types. It provides type safety and also does not negotiate the performance or productivity. Through generics, you can create generic methods, generic functions, generic classes, and generic interfaces.

In generics, a type parameter is represented between the open (<) and close (>) brackets which make a stronglytyped collection. It is denoted by a special kind of type variable . The generics collections contain only one types of object.

1. function identity(arg: T): T {

2. return arg;

3. }

4. let output1 = identity(“myString”);

5. let output2 = identity( 100 );

6. console.log(output1);

7. console.log(output2);

35. Name all object-oriented principles that TypeScript supports?

  • Encapsulation,
  • Inheritance,
  • Abstraction, and
  • Polymorphism.

36. Tell the way to check null and undefined in TypeScript?

You can use the juggling-check method to check both null and undefined:

1. if (x == null) {

2. }

Example

1. var a: number;

2. var b: number = null;

3. function check(x, name) {

4. if (x == null) {

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

6. }

7. if (x === null) {

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

9. }

10. if (typeof x === ‘undefined’) {

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

12. }

13. }

14. check(a, ‘a’);

15. check(b, ‘b’);

Output

1. “a == null”

2. “a is undefined”

3. “b == null”

4. “b === null”

37. How to use TypeScript on the backend?

Here are some examples which tell you how to use the TypeScript on the backend. Firstly we need to choose Node.js and have some additional safety types and the other required abstraction that the language brings.

Install Typescript compiler

1. npm i -g typescript

Compile using tsconfig.json file.

1. {

2. “compilerOptions”: {

3. “target”: “es5”,

4. “module”: “commonjs”,

5. “declaration”: true,

6. “outDir”: “build”

7. }

8. }

Compile ts files

1. tsc

Run

1. node build/index.js

38. Explain how an interface is different from type statements?

1. interface X {

2. a: number

3. b: string

4. }

5. type X = {

6. a: number

7. b: string

8. };

Differences are as follows:

  • Interface declaration is a named object type whereas the type aliases can be any kind of type, including primitive, union, and intersection types.
  • It can be named in an extends or implements clause and type aliases cannot be named in these clauses.
  • It creates a new name that is used everywhere and on the other hand, Type aliases don’t create a new name

39. Explain Ambients and their use in TypeScripts?

Ambient declarations tell the location of the actual source code to the compiler. If there are no source codes that existed at runtime and still, we use them, then it breaks without warning. These Ambients are like docs files. If the source changes, then the docs also need to be updated. If the doc file is not updated, then there will be compiler errors. The Ambient declarations permit us to easily and safely use the existing JavaScript libraries like jquery, angularjs, nodejs, etc

40. Explain TypeScript Map file?

  • It is basically a source map file that contains information on original files.
  • .map files are source map file that allows tools to map between the emitted JavaScript and TypeScript code source files that created it.
  • Many debuggers utilize these files to debug the TypeScript file instead of the JavaScript file.

41. Describe Type assertions in TypeScript?

It works as a typecasting in other programming languages, but it doesn’t execute type checking or restructuring of data as we can do in C# and Java. There is no impact on runtime in type assertion. Nonetheless, type assertions are only used by the compiler.

Example

1. let empCode: any = 111;

2. let employeeCode = code;

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

42. Explain "as" syntax in TypeScript?

It is an additional syntax for Type assertion. The main reason to add as-syntax is that the () syntax conflicts with JSX.

Example

1. let empCode: any = 111;

2. let employeeCode = code as number;

If you are using TypeScript with JSX only “as” syntax style assertions are used.

43. Explain JSX and its use in TypeScript?type

JSX is a Javascript with a different extension. This new extension helps in distinguishing the XML-like implementation of HTML in JavaScript. It is an embeddable XML-like syntax that transforms into valid JavaScript. It became popular with the React framework. TypeScript supports many features like embedding, type checking, and most importantly compiling JSX directly into JavaScript.

To use JSX, these two things are essentially required.

  • Name the files with a .tsx extension
  • Enable the jsx option

44. Describe Rest parameters?

It is used to pass zero or more values to a function. To declare the rest parameters you need to prefix the three dots ('…') before the parameter. It permits the functions to contain a variable number of arguments without any use of the arguments object. It is helpful where we don’t know the number of parameters.

Rules to follow in rest parameter:

  • You can use only one rest parameter in a function.
  • It must be an array type.
  • In the parameter list, the rest parameters need transforms to be last.

1. function sum(a: number, …b: number[]): number {

2. let result = a;

3. for (var i = 0; i < b.length; i++) {

4. result += b[i];

5. }

6. console.log(result);

7. }

8. let result1 = sum(3, 5);

9. let result2 = sum(3, 5, 7, 9);

45. What do you understand by Enum in TypeScript?

Enumerations or Enums is a TypeScipt data type that permits you to define a set of named constants. Enums can make document intent easy and create a set of distinct cases as well. It is a collection of different values which can be numeric or string values.

Example

1. enum Gender {

2. Male,

3. Female

4. Other

5. }

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

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

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

46. Explain parameter destructuring?

It allows a function to unload the object given as an argument into one or more local variables. For example:

function multiply({ a, b, c }: { a: number; b: number; c: number }) {

console.log(a * b * c);

}

multiply({ a: 1, b: 2, c: 3 });

Use an interface or a named type to simplify the code, like:

type ABC = { a: number; b: number; c: number };

function multiply({ a, b, c }: ABC) {

console.log(a * b * c);

}

multiply({ a: 1, b: 2, c: 3 });

47. Explain anonymous function?

An anonymous function is a function that doesn’t have any named identifier. These functions are declared at runtime. These functions can receive inputs and return outputs, as regular functions do. An anonymous function is usually not available after its initial creation.

Example

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

2. return x + y;

3. };

4. console.log(myAdd())

48. Explain Declaration Merging?

It is a process of a compiler to merge two or more declarations. The declaration needs to be declared with the same name in one definition. This merged definition contains features of both original declarations.

Example

1. interface Cloner {

2. clone(animal: Animal): Animal;

3. }

4. interface Cloner {

5. clone(animal: Sheep): Sheep;

6. }

7. interface Cloner {

8. clone(animal: Dog): Dog;

9. clone(animal: Cat): Cat;

10. }

To create a single declaration, the three interfaces will merge as so:

1. interface Cloner {

2. clone(animal: Dog): Dog;

3. clone(animal: Cat): Cat;

4. clone(animal: Sheep): Sheep;

5. clone(animal: Animal): Animal;

6. }

49. Explain the overriding method in TypeScript?

If child class (subclass) contains a similar method as declared in the parent class then it is called overriding.

Rules for Method Overriding

  • The method must have a similar name as used in the parent class
  • The method must have child class parameters as used in the parent class.
  • Must have an IS-A relationship (inheritance).

Example

1. class NewPrinter extends Printer {

2. doPrint(): any {

3. super.doPrint();

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

5. }

6. doInkJetPrint(): any {

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

8. }

9. }

10. let printer: new () => NewPrinter;

11. printer.doPrint();

12. printer.doInkJetPrint();

50. Explain Lambda/Arrow function?

ES6 Typescript version has shorthand syntax for describing the anonymous function, i.e., for function expressions. A lambda function or arrow function is a nameless function i.e. without a name. Arrow function ignores the function keyword.

Example

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

return a + b;

}

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

In the above example,

  • the ?=>? represents lambda operator
  • (a + b) represents the body of the function
  • (a: number, b: number) represents inline parameters.

Want to prepare for these languages:

Recent Articles