TypeScript Interview Questions and Answers

TypeScript Interview Questions and Answers

Last updated on 04th Jul 2020BlogInterview Questions

Ratings 7

These TypeScript Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of TypeScript . As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer.we are going to cover top 100 TypeScript  Interview questions along with their detailed answers. We will be covering TypeScript  scenario based interview questions, TypeScript  interview questions for freshers as well as TypeScript  interview questions and answers for experienced.

1. What is Typescript?

Ans:

  • 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.

2.How is TypeScript different from JavaScript?

Ans:

TypeScript is different from JavaScript in the following manner:

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

3. Why do we need TypeScript?

Ans:

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?

Ans:

Typescript-features

.

5. List some benefits of using Typescript?

Ans:

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 JavaScript points 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?

Ans:

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?

Ans:

The TypeScript has mainly three components. These are-

components-of-TypeScript

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.

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

Ans:

  • 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.

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

Ans:

  • 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.
  • $ npm install -g typescript  
  • 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:
  • 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

10. List the built-in types in Typescript.

Ans:

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

built-in types
  • 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;

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

Ans:

  • 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];

12. How to compile a Typescript file?

Ans:

  • Here is the command which is followed while compiling a Typescript file into JavaScript.
  • $ tsc <TypeScript File Name>  

For example, to compile “Helloworld.ts.”

  • $ 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?

Ans:

  • Yes, it is possible. For this, we need to add –outFILE [OutputJSFileName] compiling option.
  • $ tsc –outFile comman.js file1.ts file2.ts file3.ts  
  • 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.
  • $ tsc –outFile file1.ts file2.ts file3.ts  
  • 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.

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

Ans:

  • 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
  • tsc –watch file1.ts  
  • 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.

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

Ans:

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:

  • interface interface_name {    
  •           // variables’ declaration    
  •           // methods’ declaration    
  • }    

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.

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

Ans:

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:

  • 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?

Ans:

No. Currently, modules are not supported by Native JavaScript. To create and work with modules in Javascript we require an external like CommonJS.

18. Which object oriented terms are supported by TypeScript?

Ans:

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

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

Ans:

super() function is used to called parent or base class constructor from Child Class.

20. How do you implement inheritance in TypeScript?

Ans:

  • 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.
  • 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. What are the Modules in Typescript?

Ans:

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.

  • module module_name{  
  •     class xyz{  
  •         export sum(x, y){  
  •             return x+y;  
  •          }  
  •     }  
  • }  

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

Ans:

The difference between internal and external module is given below:

SNInternal ModuleExternal Module
1Internal 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.
2Internal 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.
3Internal 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.
4Internal 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.
5Example: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));      }  }

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

Ans:

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.

Syntax for creating namespace

  • namespace <namespace_name> {    
  •            export interface I1 { }    
  •            export class c1{ }    
  • }    

24. Explain Decorators in Typescript?

Ans:

  • 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

  • $tsc –target ES5 –experimentalDecorators    

tsconfig.json

  • {    
  •     “compilerOptions”: {    
  •         “target”: “ES5”,    
  •         “experimentalDecorators”: true    
  •     }    
  • }    

25. What are Mixins?

Ans:

  • 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.

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

Ans:

Public is the default visibility for properties/methods in TypeScript classes.

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

Ans:

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.

  • function Demo(arg1: number, arg2? :number) {              
  • }So, arg1 is always required, and arg2 is an optional parameter.   

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

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

28. Does TypeScript supports function overloading as JavaScript doesn’t support function overloading?

Ans:

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.

  • //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 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.

29. Is it possible to debug any TypeScript file?

Ans:

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.

  • $ tsc -sourcemap file1.ts  

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

  • //# sourceMappingURL=file1.js.map  

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

Ans:

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.

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

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.

  • $ npm install tsd -g  

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

  • $ tsd init  

Then install the definition file for jQuery.

  • tsd query jquery –action install  

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.

  • /// <reference path=”typings/jquery/jquery.d.ts” />  
  • $(document).ready(function() { //To Do  
  • });  
  • 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.

31. What is TypeScript Declare Keyword?

Ans:

  • 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:
  • declare var myLibrary;  
  • 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.

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

Ans:

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.

  1. tsc –declaration file1.ts  

33. What is tsconfig.json file?

Ans:

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.

  • {  
  •    “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?

Ans:

  • 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 <T> that denotes types. The generics collections contain only similar types of objects.
  • function identity<T>(arg: T): T {      
  •     return arg;      
  • }      
  • let output1 = identity<string>(“myString”);      
  • let output2 = identity<number>( 100 );    
  • console.log(output1);    
  • console.log(output2);     

35. Does TypeScript support all object-oriented principles?

Ans:

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?

Ans:

  • By using a juggling-check, we can check both null and undefined:
  • if (x == null) {  
  • }  
  • 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

  • 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

  1. “a == null”  
  2. “a is undefined”  
  3. “b == null”  
  4. “b === null”  

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

Ans:

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.

Install Typescript compiler

  • npm i -g typescript  
  • The TypeScript compiler takes options in the tsconfig.json file. This file determines where to put built files.
  • {  
  •   “compilerOptions”: {  
  •     “target”: “es5”,  
  •     “module”: “commonjs”,  
  •     “declaration”: true,  
  •     “outDir”: “build”  
  •   }  
  • }  
  • Compile ts files
  • tsc  
  • Run
  • node build/index.js

38. What is the difference between “interface vs type” statements?

Ans:

  • interface X {  
  •     a: number  
  •     b: string  
  • }  
  • type X = {  
  •     a: number  
  •     b: string  
  • };  
SNinterfacetype
1An 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.
2An 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.
3Interfaces create a new name that is used everywhere.Type aliases don’t create a new name.
4An 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?

Ans:

  • 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.

40. What is a TypeScript Map file?

Ans:

  • 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?

Ans:

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

  • let empCode: any = 111;     
  • let employeeCode = <number> code;     
  • console.log(typeof(employeeCode)); //Output: number  

42. What is “as” syntax in TypeScript?

Ans:

The as is the additional syntax for Type assertion in TypeScript. The reason for introducing the as-syntax is that the original syntax (<type>) conflicted with JSX.

Example

  • let empCode: any = 111;     
  • let employeeCode = code as number;   

When using TypeScript with JSX, only as-style assertions are allowed.

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

Ans:

  • 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.

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

44. What is Rest parameters?

Ans:

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:

  • 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(3, 5);    
  • let result2 = sum(3, 5, 7, 9);   

45. Explain Enum in TypeScript?

Ans:

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

  • 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.

Ans:

Non-RelativeRelative
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”;

47. What is an anonymous function?

Ans:

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

  • let myAdd = function(x: number, y: number): number {   
  • return x + y;   
  • };  
  • console.log(myAdd())  

48. What is Declaration Merging?

Ans:

  • 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

  • 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 merge to create a single declaration as so:

  • interface Cloner {  
  •     clone(animal: Dog): Dog;  
  •     clone(animal: Cat): Cat;  
  •     clone(animal: Sheep): Sheep;  
  •     clone(animal: Animal): Animal;  
  • }  

49. What are method overriding in TypeScript?

Ans:

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

  • 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

  • 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?

Ans:

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

  • let sum = (a: number, b: number): number => {    
  •             return a + b;    
  • }    
  • console.log(sum(20, 30)); //returns 50    
  • 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.

51.why would I use it in place of JavaScript? What is TypeScript and why would I use it in place of JavaScript?

Ans:

TypeScript is a superset of JavaScript which primarily provides optional static typing, classes and interfaces. One of the big benefits is to enable IDEs to provide a richer environment for spotting common errors as you type the code. For a large JavaScript project, adopting TypeScript might result in more robust software, while still being deployable where a regular JavaScript application would run.

52. How could you check null and undefined in TypeScript?How could you check null and undefined in TypeScript?

Ans:

Just use:

  • if (value) {
  • }

It will evaluate to true if value is not:

  • null
  • undefined
  • NaN
  • empty string ”
  • 0
  • false
  •  TypesScript includes JavaScript rules.

53. How to implement class constants in TypeScript? How to implement class constants in TypeScript?

Ans:

In TypeScript, the const keyword cannot be used to declare class properties. Doing so causes the compiler to an error with “A class member cannot have the ‘const’ keyword.” TypeScript 2.0 has the readonly modifier:

  • class MyClass {
  •     readonly myReadonlyProperty = 1;
  •     myMethod() {
  •         console.log(this.myReadonlyProperty);
  •     }
  • }
  • new MyClass().myReadonlyProperty = 5; // error, readonly

54. What is getters/setters in TypeScript? What is getters/setters in TypeScript?

Ans:

TypeScript supports getters/setters as a way of intercepting accesses to a member of an object. This gives you a way of having finer-grained control over how a member is accessed on each object.

  • class foo {
  •   private _bar:boolean = false;
  •   get bar():boolean {
  •     return this._bar;
  •   }
  •   set bar(theBar:boolean) {
  •     this._bar = theBar;
  •   }
  • }
  • var myBar = myFoo.bar;  // correct (get)
  • myFoo.bar = true;  // correct (set)

55.Could we use TypeScript on backend and how?Could we use TypeScript on backend and how?

Ans:

Typescript doesn’t only work for browser or frontend code, you can also choose to write your backend applications. For example you could choose Node.js and have some additional type safety and the other abstraction that the language brings.

Install the default Typescript compiler

  • {
  •   “compilerOptions”: {
  •     “target”: “es5”,
  •     “module”: “commonjs”,
  •     “declaration”: true,
  •     “outDir”: “build”
  •   }
  • }

Compile ts files

  • tsc

Run

  • node build/index.js

56. Is that TypeScript code valid? Explain why. Is that TypeScript code valid? Explain why.

Ans:

Mid

  • Details
  • Consider:
  • class Point {
  •     x: number;
  •     y: number;
  • }
  • interface Point3d extends Point {
  •     z: number;
  • }
  • let point3d: Point3d = {x: 1, y: 2, z: 3};

Solution

Yes, the code is valid. A class declaration creates two things: a type representing instances of the class and a constructor function. Because classes create types, you can use them in the same places you would be able to use interfaces.

57. Explain how and why we could use property decorators in TS? Explain how and why we could use property decorators in TS?

Ans:

Decorators can be used to modify the behavior of a class or become even more powerful when integrated into a framework. For instance, if your framework has methods with restricted access requirements (just for admin), it would be easy to write an @admin method decorator to deny access to non-administrative users, or an @owner decorator to only allow the owner of an object the ability to modify it.

  • class CRUD {
  •     get() { }
  •     post() { }
  •     @admin
  •     delete() { }
  •     @owner
  •     put() { }
  • }

58. Are strongly-typed functions as parameters possible in TypeScript? Are strongly-typed functions as parameters possible in TypeScript?

Ans:

  • Details
  • Consider the code:
  • class Foo {
  •     save(callback: Function) : void {
  •         //Do the save
  •         var result : number = 42; //We get a number from the save operation

        //Can I at compile-time ensure the callback accepts a single parameter of type number somehow?

  •         callback(result);
  •     }
  • }
  • var foo = new Foo();
  • var callback = (result: string) : void => {
  •     alert(result);
  • }
  • foo.save(callback);

Can you make the result parameter in save a type-safe function? Rewrite the code to demonstrate.

Solution

In TypeScript you can declare your callback type like:

  • type NumberCallback = (n: number) => any;
  • class Foo {
  •     // Equivalent
  •     save(callback: NumberCallback): void {
  •         console.log(1)
  •         callback(42);
  •     }
  • }
  • var numCallback: NumberCallback = (result: number) : void => {
  •     console.log(“numCallback: “, result.toString());
  • }
  • var foo = new Foo();
  • foo.save(numCallback)

59. Does TypeScript supports function overloading? Does TypeScript supports function overloading?

Ans:

Yes, TypeScript does support function overloading but the implementation is a bit different if we compare it to OO languages. We are creating just one function and a number of declarations so that TypeScript doesn’t give compile errors. When this code is compiled to JavaScript, the concrete function alone will be visible. As a JavaScript function can be called by passing multiple arguments, it just works.

  • class Foo {
  •     myMethod(a: string);
  •     myMethod(a: number);
  •     myMethod(a: number, b: string);
  •     myMethod(a: any, b?: string) {
  •         alert(a.toString());
  •     }
  • }

60.Explain why that code is marked as WRONG? Explain why that code is marked as WRONG?

Ans:

  • Details
  • /* WRONG */
  • interface Fetcher {
  •     getObject(done: (data: any, elapsedTime?: number) => void): void;
  • }

Solution

Don’t use optional parameters in callbacks unless you really mean it. This code has a very specific meaning: the done callback might be invoked with 1 argument or might be invoked with 2 arguments. The author probably intended to say that the callback might not care about the elapsedTime parameter, but there’s no need to make the parameter optional to accomplish this – it’s always legal to provide a callback that accepts fewer arguments.

61. How would you overload a class constructor in TypeScript? How would you overload a class constructor in TypeScript?

Ans:

  • TypeScript allows you to declare overloads but you can only have one implementation and that implementation must have a signature that is compatible with all overloads. Some techniques for constructor overloading are:
  • with an optional parameter as in
  • class Box {
  •     public x: number;
  •     public y: number;
  •     public height: number;
  •     public width: number;
  •     constructor();
  •     constructor(obj: IBox); 
  •     constructor(obj?: any) {    
  •         this.x = obj && obj.x || 0
  •         this.y = obj && obj.y || 0
  •         this.height = obj && obj.height || 0
  •         this.width = obj && obj.width || 0;
  •     }   
  • }

default parameters

  • class Box {
  •     public x: number;
  •     public y: number;
  •     public height: number;
  •     public width: number;
  •     constructor(obj : IBox = {x:0,y:0, height:0, width:0}) {    
  •         this.x = obj.x;
  •         this.y = obj.y;
  •         this.height = obj.height;
  •         this.width = obj.width;
  •     }   
  • }

additional overloads as static factory methods

  • class Person {
  •     static fromData(data: PersonData) {
  •         let { first, last, birthday, gender = ‘M’ } = data 
  •         return new this(
  •             `${last}, ${first}`,
  •             calculateAge(birthday),
  •             gender
  •         )
  •     }
  •     constructor(
  •         public fullName: string,
  •         public age: number,
  •         public gender: ‘M’ | ‘F’
  •     ) {}
  • }
  • interface PersonData {
  •     first: string
  •     last: string
  •     birthday: string
  •     gender?: ‘M’ | ‘F’
  • }
  • let personA = new Person(‘Doe, John’, 31, ‘M’)
  • let personB = Person.fromData({
  •     first: ‘John’,
  •     last: ‘Doe’,
  •     birthday: ’10-09-1986′
  • })

using union types

  • class foo {
  •     private _name: any;
  •     constructor(name: string | number) {
  •         this._name = name;
  •     }
  • }
  • var f1 = new foo(“bar”);
  • var f2 = new foo(1);

62. Explain when to use “declare” keyword in TypeScript Explain when to use “declare” keyword in TypeScript

Ans:

  • The TypeScript declare keyword is used to declare variables that may not have originated from a TypeScript file.
  • For example, lets imagine that 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 you want to use that library in your TypeScript code, you can use the following code:
  • declare var myLibrary;
  • The type that the TypeScript runtime will give to myLibrary variable is the any type. The problem here is that you won’t have Intellisense for that variable in design time but you will be able to use the library in your code. Another option to have the same behavior without using the declare keyword is just using a variable with the any type:
  • var myLibrary: any;
  • Both of the code examples will result in the same JavaScript output but the declare example is more readable and expresses an ambient declaration.

63. Is it possible to generate TypeScript declaration files from JS library?Is it possible to generate TypeScript declaration files from JS library?

Ans:

  • JavaScript doesn’t always contain enough type information for the TypeScript compiler to infer the structures in your code – so automatically generating a definition based on JavaScript is rarely an option but:
  • Microsoft/dts-gen – The official starting point Microsoft uses when creating types
  • dtsmake – This one looks very promising. It depends on Ternjs which some editors use to provide autocomplete for JS code.

64. What are Mixins in TypeScript?

Ans:

In Javascript Mixins are another way of building up classes from reusable components is to build them by combining simpler partial classes.

65. Who developed Typescript and what is the current stable version of Typescript?

Ans:

Typescript was developed by Anders Hejlsberg in 2012, who is the lead architect of C# and the creator of Delphi and Turbo Pascal. Typescript is a free and open source programming language maintained by Microsoft. It is a superset of JavaScript. It was developed for the development of large application. The current stable version of this programming language is 2.7.0-beta-20171212 which was released on December 12, 2017. Typescript compiles to simple JavaScript code which runs on any browser that supports ECMAScript 3 framework. It offers support for the latest and evolving JavaScript features.

66. What are variables in Typescript? How to create a variable in Typescript?

Ans:

  • A variable is a named space in the memory which stores a particular value. While declaring a variable in Typescript, certain rules should be followed like-
  • A variable name should contain alphabets and numeric digits.
  • It cannot contain spaces and special characters except underscore (_) and dollar ($) sign.
  • A variable name cannot begin with a digit.
  • You should always keep in mind, that a variable should be declared before being used. Variables in Typescript are declared by placing a “var” keyword prior to the variable name. A variable can be declared using 4 methods: –
  • Declare its type and value in one statement.Syntax- var variable_name:string = value;
  • Declare its type but no value.Syntax- var variable_name:string;
  • Declare its value but no type.Syntax- var variable_name = value;
  • Declare neither value nor type.Syntax- var variable_name;

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

Ans:

We all know that Typescript is a type of object-oriented JavaScript and supports object-oriented programming features like- classes, interfaces, etc. Here, a class in terms of object-oriented programming is a blueprint for creating objects. A class is used to encapsulate data for the object. A built-in support is provided by Typescript for this feature. The “class” keyword is used to declare a class in Typescript.

Example

  • class Greeter {
  •     greeting: string;
  •     constructor (message: string) {
  •         this.greeting = message;
  •     }
  •     greet() {
  •         return “Hello, ” + this.greeting;
  •     }
  • }  

Some features of a class are-

  • Encapsulation i.e. creation of self-contained modules that bind processing functions to the data, takes place.
  • Classes are created in hierarchies and with the help of inheritance; the features of one class can be used in the other.
  • Polymorphism takes place.
  • Abstraction

68. What are Closures in Javascript?

Ans:

  • Closures are nothing but a statefull functions.
  • A closure is an inner function that has access to outer function’s variables in addition to it’s own variable and global variables.In simple term a closure is a function inside a function.Closures using Lexical scoping in which function have access to global and outer variables.Below is a sample example of Javascript closure.
  • function employee() {
  •     var employee_dept = ‘IT’;
  •     return {
  •         getDept: function ()  {           
  •           return employee_dept;
  •         },
  •         setDept: function (new_dept)  {
  •             employee_dept = new_name;
  •         }
  •     }
  • }
  • var emp1 = employee (); // In this juncture, the employee_dept outer function has returned.​
  • mjID.getDept(); // IT
  • mjID.setDept(‘Account’); // Changes the outer function’s variable​
  • mjID.getDept(); //outputs Account
  • Closures prevents your important variable to be modified accidently.It can be only modified by itself.

69. List types of scopes available in Javascript?

Ans:

There are two types of scopes are available in Javascript, they are

  • Global Scope
  • Local Scope

70. Explain Decorators in Typescript? List type of Decorators available in Typescript?

Ans:

  • Decorators are function that supports annotating or modifying classes its members.Its allow way to add both annotations and a meta-programming syntax for class declarations and members. Decorators are an experimental feature of Typescript and maybe change in future releases.
  • You can enable Decorators using the command line or editing your tsconfig.json
  • Enabling Decorators in TypeScript via command line
  • tsc –target ES5 –experimentalDecorators

71. Explian Type assertions in TypeScript?

Ans:

Type assertion allows you to set the type of a value. After the value set, typescript told the compiler not to assume the type of value.

72. What is an Interface in TypeScript?

Ans:

The classes in TypeScript must follow the structure of the interface. The interface contains the method declaration, variable declaration.

73. What is an implicit Module in Typescript?

Ans:

A module is used to create a set of related variables, functions, classes, and interfaces, etc in the Typescript. The internal and external module has two categories of Typescript.

74.What is duck typing in TypeScript?

Ans:

Duck-typing used to check the type compatibility for more complex variable types in typescript. This method checks the type matching between two objects. If the property contains more or less or not match then a compile-time error occurred.

75. why do we need it?

Ans:

  •  JavaScript is the only client side language universally supported by all browsers. But JavaScript is not the best designed language. It’s not a class-based object-oriented language, doesn’t support class based inheritance, unreliable dynamic typing and lacks in compile time error checking. And TypeScript addresses all these problems. In other words, TypeScript is an attempt to “fix” JavaScript problems.
  • TypeScript is a free and open source programming language developed and maintained by Microsoft. It is a strict superset of JavaScript, and adds optional static typing and class-based object-oriented programming to the language. TypeScript is quite easy to learn and use for developers familiar with C#, Java and all strong typed languages. At the end of day “TypeScript is a language that generates plain JavaScript files.”
  • As stated on Typescript official website, “TypeScript lets you write JavaScript the way you really want to. TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. Any browser. Any host. Any OS. Open Source.” Where “typed” means that it considers the types of variables, parameters and functions.

76. What are the benefits of TypeScript?

Ans:

 TypeScript has following benefits.

  • It helps in code structuring.
  • Use class based object oriented programming.
  • Impose coding guidelines.
  • Offers type checking.
  • Compile time error checking.
  • Intellisense.

77. What are different components of TypeScript?

Ans:

 There are mainly 3 components of TypeScript .

  • Language – The most important part for developers is the new language. The language consist of new syntax, keywords and allows you to write TypeScript.
  • Compiler – The TypeScript compiler is open source, cross-platform and open specification, and is written in TypeScript. Compiler will compile your TypeScript into JavaScript. And it will also emit error, if any. It can also help in concating different files to single output file and in generating source maps.
  • Language Service – TypeScript language service which powers the interactive TypeScript experience in Visual Studio, VS Code, Sublime, the TypeScript playground and other editor.

78. How can you get TypeScript and install it?

Ans:

 TypeScript can be installed and managed via npm, the Node.js package manager. To install TypeScript, first ensure the npm is installed properly. And then run following command to install TypeScript globally on your system.

  • npm install -g typescript
  • TypeScript is included in Visual Studio 2013 Update 2 and Visual Studio 2015 by default. TypeScript also provides support for other editors like Visual Studio Code, sublime, Emacs and Vim.

79. How do you compile TypeScript files?

Ans:

 The extension for any TypeScript file is “.ts”. And any JavaScript file is TypeScript file as it is a superset of JavaScript. So change extension of “.js” to “.ts” file and your TypeScript file is ready. To compile any .ts file into .js use following command.

  • tsc <TypeScript File Name>

For example, to compile “Helloworld.ts”

  • tsc helloworld.ts

And the result would be helloworld.js

80. Which are the different data types supported by TypeScript?

Ans:

 TypeScript supports following data types.

  • Boolean var bValue: boolean = false;
  • Number var age: number = 16;
  • String var name: string = “jon”;
  • Array var list:number[] = [1, 2, 3];
  • Enum
  • enum Color {Red, Green, Blue};var c: Color = Color.Green;
  • Any var unknownType: any = 4;
  • Void
  • function NoReturnType(): void {}

81. How TypeScript is optionally statically typed language?

Ans:

 TypeScript is referred as optionally statically typed, which means you can ask the compiler to ignore the type of a variable. Using any data type, we can assign any type of value to the variable. TypeScript will not give any error checking during compilation.

  • var unknownType: any = 4;unknownType = “Okay, I am a string”;unknownType = false; // A boolean.

82. What are classes in TypeScript?

Ans:

 The concept of classes is very similar to .Net/Java. A Class can have constructor, member variables, properties and methods. TypeScript also allows access modifiers “private” and “public” for member variables and functions.

83. What is the default access modifier for members of a class in TypeScript?

Ans:

 In TypeScript, each member of class is public by default.

84. How can you allow classes defined in a module to accessible outside of the module?

Ans:

 Classed define in a module are available within the module. Outside the module you can’t access them.

  • module Vehicle {    class Car {        constructor (            public make: string,            public model: string) { }    }    var audiCar = new Car(“Audi”, “Q7”);}// This won’t workvar fordCar = Vehicle.Car(“Ford”, “Figo”);

As per above code, fordCar variable will give us compile time error. To make classes accessible outside module use export keyword for classes.

  • module Vehicle {    export class Car {        constructor (            public make: string,            public model: string) { }    }    var audiCar = new Car(“Audi”, “Q7”);}// This works nowvar fordCar = Vehicle.Car(“Ford”, “Figo”);

85. How to create an object in typescript?

Ans:

In Typescript, an object is used to store a set of key-value pairs. Following is a syntax for creating an object in Typescript:

Example

  • var object_name = {
  • key1: “value1”,
  • key2: “value”,
  • key3: function()
  • },
  • key4:[“content1”, “content2”]
  • };

86. What is the advantage of Arrow function in TypeScript?

Ans:

The two significant benefits that Arrow function in TypeScript offers:

  • They are less verbose compared to traditional functions.
  • This function takes the “this” from its surroundings.

87. How to write a function in typescript?

Ans:

In Typescript, a function in TypeScript can be written in two ways:

Named Function

This type of function is written and called using its own name.

Example:

  • function display() {
  • console.log(“Hello Best Interview Question Team!”);
  • }
  • display(); //Output: Hello Best Interview Question Team

Anonymous Function

In this function, the code is written and stored through expressions or variables. The variable/expression name is used to call the stored data types.

Example:

  • let greeting = function() {
  • console.log(“Hello Best Interview Question Team”);
  • };
  • greeting(); //Output: Hello Best Interview Question Team

88. What is the difference between TypeScript and es6?

Ans:

S.noTypeScriptES6
1.Extremely comfortable to eradicate the development error.ES6 is more comfortable in development deployment.
2.It’s an open source programming language.It’s a scripting language.
3.It supports all primitive data types.ES6 doesn’t support primitive data types.
4.TypeScript has 3 scopes: Global, Class, and Local.It has only two scopes: Global and Local.

89. Why is TypeScript strongly typed?

Ans:

TypeScript is strongly typed to syntactical benefits to this language while still allowing users to write normal JavaScript. It also ensures the production of predictable results with fewer errors and more secure.

90. What is static typing in TypeScript?

Ans:

In TypeScript, static typing means parameters, variables, and object members have types that compiler recognizes at the time of compile. This helps in detecting early errors faster than unit test runs. It also greatly helps IDEs with auto-completion and API exploration with statically typed DOM. Static typing is an important chapter which supports a number of TypeScript Interview Questions, so it’s crucial to practice this one.

91. What is the prototype in TypeScript?

Ans:

The prototype property in TypeScript allows users to include methods and properties to an object. It allows cloning objects (complex ones also) without coupling to their specific classes. Prototype objects can create full copies due to the accessibility of objects to each other’s private field.

92. What is the callback function in TypeScript?

Ans:

In TypeScript, the callback function is used to schedule a call after some asynchronous processing is completed. It is passed to another function as a parameter that allows callback function to be called when the process of asynchronous processing is completed.

93. How to declare a module in TypeScript?

Ans:

Here’s how to declare modules in Typescript:

Declaring any of the external modules having no exposed types or values:

  • declare module ‘Foo’ {
  •    var x: any;
  •    export = x;
  • }

For declaring individual classes

  • declare module ‘Foo’ {
  • export type cls = any;
  • export var cls: any;

94. How to import a module in typescript?

Ans:

  • Modules can be imported using the import keyword. Here’s a detailed info into it:
  • Importing individual exports from within a module:
  • import { Employee } from “./Employee”;
  • import * as Emp from “./Employee”
  • console.log(Emp.age); // 10

95. How to call typescript function from JavaScript?

Ans:

Compiling Typescript into Javascript is done using a JS function. During this process of compiling, the code structure could be changed a bit. If you have multiple modules or classes in the typescript, then they would become a part of the path to call the specific function.

Example

  • class Foo{
  •   constructor(){}
  •   public Bar = () : string =>{
  •       return “This is a string”;
  •   }
  • }
  • module FooModule {
  •   export var FooInstance = new Foo();
  • }

If you would want to call this in Typescript, use this command:

  • FooModule.FooInstance.Bar();

96. How to install TypeScript on windows?

Ans:

Steps to install TypeScript environment in Windows are given below.

  • First, download the latest version of TypeScript from its official website.
  • We can install TypeScript using Node.js, Visual Studio, or other supported editors, but the first two are the most common way to install it.
  • Download and run the .msi installer for Node support.
  • Then, we will use npm to install TypeScript using Node.js. Just running the below-mentioned command in the Windows command will install the latest version.
    npm install -g typescript
  • We can check the version of TypeScript by running the following command in the terminal.
    tsc -v
  • To get help for other options here, use the following command
    tsc -h
  • To install TypeScript using Visual Studio, download Visual Studio Code, and launch it.
  • Now by right clicking on the file → open in the command prompt, users may traverse to the file’s path.
  • Now, creating a TypeScript file is possible just by adding a new file with a .ts extension. All the features of TypeScript will be available out of the box

97. What is components in TypeScript? Also explain its types.

Ans:

The Typescript components comprise 3 parts. They are:

  • Language: It consists of features of the language element of Typescript. Syntax, keywords, and type annotation rules and syntax are covered in this.
  • The TypeScript Compiler: Used to compile the same code into Javascript. It also parses and checks the type of code being compiled into Javascript.
  • TypeScript Language Services: This provides information that helps editors and other tools to increase productivity by automated refactoring and Intellisense.

98. Explain access modifiers in TypeScript?

Ans:

TypeScript developers can use the access modifiers to control the accessibility of the class members. There are two types of access modifiers in TypeScript; private and public modifiers. Class members are public by default, but users can add a private modifier if they wish.

99. What is super in TypeScript?

Ans:

Super is a TypeScript keyword which can be used by developers in expressions for base class constructor and base class properties reference. This call is only allowed in constructors of derived classes. Call for this keyword consist the keyword super with an argument list closed in parentheses.

100. Which keyword is used for inheritance in TypeScript?

Ans:

TypeScript uses the keyword ‘extends’ to support inheritance. The syntax will be as following:

  • class child_class_name extends parent_class_name
ssass

Are you looking training with Right Jobs?

Contact Us
Get Training Quote for Free