0% found this document useful (0 votes)
7K views

Type Script

TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. It adds optional static types, classes, interfaces, and modules to JavaScript to improve developer productivity and code quality. The current stable version of TypeScript is 3.2. Variables in TypeScript are declared using the var keyword followed by the variable name and type separated by a colon. The built-in data types in TypeScript include number, string, boolean, null, undefined and void.

Uploaded by

R.A. Aruneash
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7K views

Type Script

TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. It adds optional static types, classes, interfaces, and modules to JavaScript to improve developer productivity and code quality. The current stable version of TypeScript is 3.2. Variables in TypeScript are declared using the var keyword followed by the variable name and type separated by a colon. The built-in data types in TypeScript include number, string, boolean, null, undefined and void.

Uploaded by

R.A. Aruneash
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 103

Q1.

What are the Differences between TypeScript and


JavaScript?
TypeScript JavaScript
TypeScript is an Object-Oriented language JavaScript is a Scripting language
It has a feature known as Static typing It does not have static typing
TypeScript gives support for modules JavaScript does not support modules
It supports optional parameter function It does not support optional parameter function

Q2. What is TypeScript?

TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. It is


pure object-oriented with classes, interfaces and statically typed programming
languages like C# or Java. You will need a compiler to compile and generate the code
in the JavaScript file. Basically, TypeScript is the ES6 version of JavaScript with some
additional features.

Syntax:

1 var message:string = "Welcome to Edureka!"


2 console.log(message)

A TypeScript code is written in a file with .ts extension and then compiled into
JavaScript using the compiler. You can write the file in any code editor and the compiler
needs to be installed on your platform. After the installation, the command tsc
<filename>.ts compiles the TypeScript code into a plain JavaScript file.

Q3. Why do we need TypeScript?

There are different reasons why a JavaScript developer should consider using
TypeScript. Some of them include:

 Using new features of ECMAScript: TypeScript supports new ECMAScript


standards and transpile them to ECMAScript targets of your choice. So, you can
use features of ES2015 and beyond.
 Static Typing: JavaScript is dynamically typed and does not know what type a
variable is until it is actually instantiated at run-time. TypeScript adds type
support to JavaScript.

 Type Inference: TypeScript makes typing a bit easier and a lot less explicit by
the usage of type inference. Even if you don’t explicitly type the types, they are
still there to save you from doing something which otherwise would result in a
run-time error.

 Better IDE Support: The development experience with TypeScript is a great


improvement over JavaScript. There is a wide range of IDEs that have excellent
support for TypeScript, like Visual Studio & VS code, Atom, Sublime, and
IntelliJ/WebStorm.

 Strict Null Checking: Errors, like cannot read property ‘x’ of undefined, is
common in JavaScript programming. You can avoid most of these kinds of errors
since one cannot use a variable that is not known to the TypeScript compiler.

 Interoperability: TypeScript is closely related to JavaScript so it has great


interoperability capabilities, but some extra work is required to work
with JavaScript libraries in TypeScript.

Q4. Mention some of the features of TypeScript

 Cross-Platform: The TypeScript compiler can be installed on any Operating


System such as Windows, MacOS, and Linux.

 Object-Oriented Language: TypeScript provides features like Classes,


Interfaces, and Modules. Thus, it can write object-oriented code for client-side as
well as server-side development.
 Static Type-Checking: TypeScript uses static typing and helps type checking at
compile time. Thus, you can find errors while writing the code without running the
script.

 Optional Static Typing: TypeScript also allows optional static typing in case you
are using the dynamic typing of JavaScript.

 DOM Manipulation: You can use TypeScript to manipulate the DOM for adding
or removing elements.

 ES 6 Features: TypeScript includes most features of planned ECMAScript 2015


(ES 6, 7) such as class, interface, Arrow functions, etc.

Q5. What are the Benefits of using TypeScript?

The Benefits of using TypeScript are:

 TypeScript is fast, simple, easy to learn and runs on any browser or JavaScript
engine.

 It is similar to JavaScript and uses the same syntax and semantics.

 This helps backend developers write front-end code faster.

 You can call the TypeScript code from an existing JavaScript code. Also, it
works with existing JavaScript frameworks and libraries without any issues.

 The Definition file, with .d.ts extension, provides support for existing JavaScript
libraries like Jquery, D3.js, etc.

 It includes features from ES6 and ES7 that can run in ES5-level JavaScript
engines like Node.js.

Q6. What are the Disadvantages of TypeScript?

TypeScript has the following disadvantages:

 TypeScript takes a long time to compile the code.

 It 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 for decades and TypeScript doesn’t bring
anything new.

 To use any third party library, the definition file is a must.

 Quality of type definition files is a concern.

Q7. What are the Components of TypeScript?

There are three different types of components in TypeScript which includes:

 Language − It comprises of the syntax, keywords, and type annotations.

 The TypeScript Compiler − This compiler (tsc) converts the instructions written
in TypeScript to its JavaScript equivalent.

 The TypeScript Language Service − The Language Service exposes an


additional layer around the core compiler pipeline, editor-like applications. The
language service supports the common set of typical editor operations.

Q8. Who developed Typescript and what is the current stable version
available?

Anders Hejlsberg developed TypeScript. Also, he is 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. But, 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 the ECMAScript 2015 framework. Also, it offers support for the latest and
evolving JavaScript features.

Q9. How to install TypeScript?

There are two main ways to install TypeScript tools such as:

1. Via npm (Node.js Package Manager) command-line tool

npm install -g typescript

2. By installing TypeScript via Visual Studio.

If you use Visual Studio or VS Code IDE, the easiest way to add to Visual Studio or VS
Code is to search and add a package or download from the TypeScript website. Also,
you can download TypeScript Tools for Visual Studio.

Q10. How do you compile TypeScript files?


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

tsc <TypeScript File Name>

For example, to compile “edureka.ts”

tsc edureka.ts

And the result would be edureka.js

Q11. Can we combine multiple .ts files into a single .js file?

Yes, we can combine multiple files. While compiling, we need to add –outFILE
[OutputJSFileName] option.

tsc --outFile comman.js file1.ts file2.ts file3.ts

This will compile all 3 “.ts” file and output into a single “comman.js” file.

tsc --outFile file1.ts file2.ts file3.ts

If you don’t provide an output file name, file2.ts and file3.ts will be compiled and the
output will be placed in file1.ts. So now your file1.ts contains JavaScript code.

Q12. What are the different types of TypeScript?

The Type System represents the different types of values supported by the language. It
checks the validity of the supplied values before they are stored or manipulated by the
program.
It can be classified into two types such as:

 Built-in: This includes number, string, boolean, void, null and undefined.
 User-defined: It includes Enumerations (enums), classes, interfaces, arrays, and
tuple.

Q13. List out the built-in data types in TypeScript.

In TypeScript, the built-in data types are also known as primitive data types and the list
include:

 Number: This represents number type values. The numbers are stored as
floating-point values in TypeScript.
 String: A string represents a sequence of characters stored as Unicode UTF-16
code.
 Boolean: This represents a logical value. When we use the Boolean type, we get
the output only in true or false.
 Null: Null represents a variable whose value is undefined. It is not possible to
directly reference the null type value itself.
 Undefined: The Undefined type denotes all uninitialized variables.
 Void: A void is the return type of the functions that do not return any type of
value.

Q14. What are Variables in TypeScript and how to create them?

A variable is a named space in the memory which is used to store values. The type
syntax for declaring a variable in TypeScript includes a colon (:) after the variable name,
followed by its type. Similar to JavaScript, we use the var keyword to declare a variable.
While declaring a variable in Typescript, certain rules must be followed-

 The variable name must be an alphabet or numeric digits.


 You cannot start the name with digits.
 It cannot contain spaces and special characters, except the underscore(_) and
the dollar($) sign.

Q15. What are the different ways of declaring a Variable?

There are four ways of declaring a variable:


var [identifier] : [type-annotation] = value; //Declaring type and value in a single statement
var [identifier] : [type-annotation]; //Declaring type without value
var [identifier] = value; //Declaring its value without type
var [identifier]; //Declaring without value and type

Q16. Is it possible to compile .ts automatically with real-time changes


in the .ts file?

Yes, we can compile “.ts” automatically with real-time changes in the .ts file. This can
be done 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 once again. Here, we need to
ensure that the command prompt must not be closed on running with –watch option.

Q17. What are the object-oriented terms supported by TypeScript?

TypeScript supports the following object-oriented terms:

 Modules
 Classes
 Interfaces
 Inheritance
 Data Types
 Member functions
Q18. What are Interfaces in TypeScript?

The interface is a structure that defines the contract in your application. It defines the
syntax for classes to follow. It contains only the declaration of the members and it is the
responsibility of the deriving class to define the members. The TypeScript compiler uses
interface for type-checking and checks whether the object has a specific structure or
not.

Syntax:

1 interface interface_name {
2 // variables' declaration
3 // methods' declaration
}
4

Q19. What are Classes in TypeScript? List out some of the features.

TypeScript introduced classes so that they can avail the benefits of object-oriented
techniques like encapsulation and abstraction. The class in TypeScript is compiled to
plain JavaScript functions by the TypeScript compiler to work across platforms and
browsers.

A class includes the following:

 Constructor
 Properties
 Methods

Example:

1 class Employee {
empID: number;
2
empName: string;
3
4 constructor(ID: number, name: string) {
5 this.empName = name;
6 this.empID = ID;
7 }
8
getSalary() : number {
9 return 40000;
10 }
11 }
12
13 }
14

Some of the features of a class are:

 Inheritance
 Encapsulation
 Polymorphism
 Abstraction

Q20. What are the access modifiers supported by TypeScript?

TypeScript supports access modifiers public, private and protected which determine the
accessibility of a class member as given below:

 Public – All the members of the class, its child classes, and the instance of the
class can access.
 Protected – All the members of the class and its child classes can access them.
But the instance of the class can not access.
 Private – Only the members of the class can access them.

If an access modifier is not specified it is implicitly public as that matches the convenient
nature of JavaScript.

Q21. How is TypeScript an optionally statically typed language?

TypeScript is referred to 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.

Example:

1 var unknownType: any = 4;


2 unknownType = "Welcome to Edureka"; //string
3 unknownType = false; // A boolean.

Q22. What are modules in TypeScript?


A module is a powerful way of creating a group of related variables, functions, classes,
and interfaces, etc. It can be executed within its own scope, but not in the global scope.
Basically, you cannot access the variables, functions, classes, and interfaces declared
in a module outside the module directly.

A module can be created by using the export keyword and can be used in other
modules by using the import keyword.

Example:

1 module module_name{
2 class xyz{
3 export sum(x, y){
4 return x+y;
}
5
}
6

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

Internal Module External Module

External modules are useful in hiding the internal


Internal modules group the classes, interfaces,
statements of the module definitions and show only the
functions, variables into a single unit and can be
methods and parameters associated with the declared
exported in another module.
variable.
Internal modules were a part of the earlier version of External modules are known as a module in the latest
Typescript. version.
These are separately loaded bodies of code referenced
These are local or exported members of other modules.
using external module names.
Internal modules are declared using An external module is written as a separate source file
ModuleDeclarations that specify their name and body. that contains at least one import or export declaration.

Q24. What is namespace in Typescript and how to declare it?

Namespace groups functionalities logically. These 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:

1 namespace <namespace_name> {
2 export interface I1 { }
3 export class c1{ }
}
4

Q25. Does TypeScript support function overloading?

Yes, TypeScript supports function overloading. But the implementation is odd. So, when
you overload in TypeScript you only have one implementation with multiple signatures.

For example:

1
2 class Customer {
3 name: string;
Id: number;
4 add(Id: number);
5 add(name:string);
6 add(value: any) {
7 if (value && typeof value == "number") {
8 //Do something
}
9 if (value && typeof value == "string") {
10 //Do Something
11 }
12 }
13

The first signature has one parameter of type number whereas the second signature
has a parameter of type string. The third function contains the actual implementation
and has a parameter of type any. The implementation then checks for the type of the
supplied parameter and executes a different piece of code based on the supplier
parameter type.

Q26. Explain Decorators in TypeScript.


A Decorator is a special kind of declaration that can be applied to classes, methods,
accessor, property, or parameter. Decorators are 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. To enable experimental support for
decorators,you need to enable the experimentalDecorators compiler option either on the
command line or in our tsconfig.json:

Command Line

$tsc --target ES5 –experimentalDecorators

tsconfig.json

1 {
2 "compilerOptions": {
3 "target": "ES5",
4 "experimentalDecorators": true
}
5
}
6

Q27. What are Mixins?

In Javascript, Mixins are a way of building up classes from reusable components and
then build them by combining simpler partial classes.

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. Here,
function B is a mixin.

Q28. How does TypeScript support optional parameters in function?


Unlike JavaScript, the TypeScript compiler throws an error if you try to invoke a function
without providing the exact number and types of parameters as declared in its function
signature. To overcome this problem, you can use optional parameters by using a
question mark sign (‘?’). It indicates that the parameters which may or may not receive a
value can be appended with a ‘?’ to mark them optional.

Example:

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


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

In the above example, arg1 is always required, and arg2 is an optional parameter.

Q29. What is Scope variable?

The scope is a set of objects, variables, and function and the JavaScript can have a
global scope variable and local scope variable.

You can declare a variable in two different scopes such as:

 Local Scope Variable – It is a function object which is used within the functions

 Global Scope Variable – You can use this window object out of function and
within the functions

Q30. How can you debug a TypeScript file?

To debug any TypeScript file, you need a .js source map file. So, you have to 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 the last line of file1.js would be a reference
of the source map file.

//# sourceMappingURL=file1.js.map

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

TypeScript Definition Manager (TSD) is a package manager used to search and install
TypeScript definition files directly from the community-driven DefinitelyTyped repository.

Now, if you want to use some jQuery code in your .ts file:

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

Here, when you try to compile it by using tsc, it will give a compile-time error: Cannot
find the name “$”. So, you need to inform the TypeScript compiler that “$” is belongs
to jQuery. To do this, TSD comes into play. You can download the jQuery Type
Definition file and include it in our .ts file.

Q32. What are the steps to include Type Definition File?

The steps involved in the process of including the Type Definition File are:

 First, you have to install TSD.

$ npm install tsd -g

 Next, 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 the definition file by updating the
TypeScript file to point to the jQuery definition.

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


$(document).ready(function() { //To Do
});
 Finally, compile again. This time js file will be generated without any error.
Hence, the need for TSD helps us to get the type definition file for the required
framework.

Q33. What is TypeScript Declare Keyword?

JavaScript libraries or frameworks don’t have TypeScript declaration files. But if you
want to use them in the TypeScript file without any compilation error, you have to use
the declare keyword. The declare keyword is used for ambient declarations and
methods where you want to define a variable that may exist elsewhere.

If you want to use the library in our TypeScript code, you can use the following code:

1 declare var myLibrary;

TypeScript runtime will assign the myLibrary variable as any type.

Q34. What is the Default Parameters Function in TypeScript?

Function parameters can be assigned values by default. A parameter can’t be declared


as optional and default both at the same time.

Example:

1 let discount = function (price: number, rate: number = 0.40) {


2 return price * rate;
3 }
4 discount(500); // Result - 200
discount(500, 0.45); // Result - 225
5

In the above example, rate is a default param as number in discount function. If we pass
the value in the discount’s rate param, it will use this otherwise use default value 0.40.

Q35. What is tsconfig.json file?


The tsconfig.json file is a file which is in JSON format. In the tsconfig.json file, you can
specify different 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.

Example of a sample tsconfig.json file:

1
2 {
3 "compilerOptions": {
4 "declaration": true,
"emitDecoratorMetadata": false,
5 "experimentalDecorators": false,
6 "module": "none",
7 "moduleResolution": "node"
8 "removeComments": true,
9 "sourceMap": true
},
10 "files": [
11 "main.ts",
12 "othermodule.ts"
13 ]
}
14
15

Q36. What are Generics in TypeScript?

TypeScript Generics is a tool that provides a way of creating reusable components. It is


able to create components that can work with a variety of data types rather than a single
data type. Also, it 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. It uses a special kind of type variable <T> that
denotes types.

Example:

1 function identity<T>(arg: T): T {


2 return arg;
3 }
4 let output1 = identity<string>("edureka");
5 let output2 = identity<number>( 117 );
console.log(output1);
6 console.log(output2);
7
Q37. What is the difference between interface and type statements?

Interface Type

A type alias declaration introduces a name for any kind


An interface declaration introduces a named object type of type, including primitive, union, and intersection
types
Type alias for an object type literal cannot be named in
It can be named in an extends or implements clause.
an extends or implements clause
Interfaces create a new name that is used everywhere They don’t create any new name
It can have multiple merged declarations It cannot have multiple merged declarations

Q38. What is JSX in TypeScript?

JSX is an embeddable XML-like syntax and it is meant to be transformed into a valid


JavaScript. JSX became popular with the React framework. TypeScript supports
embedding, type checking, and compiling JSX directly into JavaScript.

If you want to use JSX in your file, you need to name your file with a .tsx extension and
enable jsx option.

Q39. What are all the JSX modes TypeScript supports?

TypeScript consists of three JSX modes:

The preserve mode keeps the JSX as part of the output to be further consumed by
another transform step. Also, the output will have a .jsx file extension. The react mode
emits React.createElement, does not need to go through a JSX transformation before
use, and the output will have a .js file extension. The react-native mode is the equivalent
of the preserve and it keeps all JSX, but the output has a .js file extension instead.
Q40. What are Ambients in TypeScripts and when to use them?

Ambient declarations tell the compiler about the actual source code that exists
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 files. If the source changes, the docs need to be
kept updated and if the ambient declaration file is not updated, then you will get
compiler errors. Also, it allows us to safely and easily use existing popular JavaScript
libraries like jquery, angularjs, nodejs, etc.

Q41. What is a TypeScript Map file?

TypeScript Map file is a source map file that holds information about our original files.
The .map files are source map files that let tools map between the emitted JavaScript
code and the TypeScript source files that created it. Also, debuggers can consume
these files so we can debug the TypeScript file instead of the JavaScript file.

Q42. What is Type assertions in TypeScript?

Type assertion works like a typecasting in other languages, but it doesn’t perform type
checking or restructuring of data in other languages 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:

1 let empCode: any = 007;


2 let employeeCode = <number> code;
3 console.log(typeof(employeeCode)); //Output: number

Q43. What are Rest parameters?

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.
Q44. What are the rules to declare Rest parameters? Give an example.

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.

Example:

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 let result1 = sum(2, 4);
8 let result2 = sum(2,4,6,8);
9

Q45. What is “as” syntax in TypeScript?

The “as” is the additional syntax for Type assertion in TypeScript. The reason for
introducing the as-syntax is that the original syntax conflicted with JSX.

Example:

1 let empCode: any = 007;


2 let employeeCode = code as number;

While using TypeScript with JSX, only as-style assertions are allowed.
Q46. Explain Enum in TypeScript.

Enums or enumerations are a TypeScipt data type that allows us to define a set of
named constants. Using enums 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:

1
enum Gender {
2 Male,
3 Female
4 Other
5 }
console.log(Gender.Male); // Output: 0
6
//We can also access an enum value by it's number value.
7 console.log(Gender[1]); // Output: Female
8

Q47. Explain Relative and Non-relative module imports.

Relative Non-Relative

A non-relative import can be resolved relative to


Relative imports can be used for our own modules that are
baseUrl, or through path mapping. In other words, we
guaranteed to maintain their relative location at runtime. A
use non-relative paths when importing any of our
relative import is starts with /, ./ or ../.
external dependencies.
Example:
Example:
import Entry from "./components/Entry";
import * as $ from "jquery"; import {DefaultHeaders} from "../constants/http";
import { Component } from "@angular/core";

Q48. What is an anonymous function?

An anonymous function is a function that is declared without any named identifier.


These functions are dynamically declared at runtime. Also, anonymous functions can
accept inputs and return outputs, just as standard functions do. It is usually not
accessible after its initial creation.

Example:

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


return a+b;
2
};
3 console.log(myAdd())
4

Q49. What is method overriding in TypeScript?

If the subclass or the child class has the same method as declared in the parent class, it
is known as method overriding. Basically, it redefines 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
 It must have the same parameter as in the parent class.
 There must be an IS-A relationship or inheritance.

Q50. What is Lambda/Arrow function?

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. Whereas, the arrow function
omits the function keyword.

Example:

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


2 return x + y;
3 }
console.log(sum(10, 20)); //returns 30
4

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

What is Typescript?
Typescript is a superset of JavaScript which primarily provides optional static typing, classes, and
interfaces. We have written some Refined interview questions on Typescript that helps developers to
crack interview on TypeScript.

Below are the list of some Typescript Interview Questions and their answers that may be asked by an
interviewer in your interview
Quick Questions about Typescript
Typescript is subset of Javascript.

Typescript is Licensed under Apache License 2.0

Typescript is Designed by Microsoft Corporation

Typescript file extension ts,.tsx

Typescript is released on 1 October 2012

Typescript is based on Duck, gradual, structural typing discipline

1) What is Typescript?

Typescript is a free and open-source programming language which is designed and


developed by Microsoft. It was designed by Anders Hejlsberg at Microsoft. Typescript
is a superset of JavaScript which primarily provides optional static typing, classes and
interfaces. Typescript is compiled to provide clean and simple JavaScript code which
runs on any browser. It allows JavaScript developers for using highly productive
development tools and practices like static checking and code refactoring.
Differences between Typescript and JavaScript are

1. JavaScript don’t support Es6 while Typescript supports .


2. JavaScript build up reusable components by using unctions and prototype-based
inheritance while Typescript supports Classes that allow programmer to think in
more object oriented way .
3. JavaScript don’t have any interfaces while Typescript has interfaces.
4. There is no static typing in JavaScript whereas there is static typing in Typescript.
5. JavaScript has no optional parameter feature while Typescript has optional
parameter feature.

2) What are generics in TypeScript?


3) List some features of Typescript?

Features of Typescript are:-

 Typescript can be compiled to all major versions of


Javascript(ES3,ES5,ES6,ES7).
 Typescript can be used for cross –browser development and is an open source
project.
 Typescript is a superset of JavaScript that provides typed nature to your code.
 It is used to avoid the disadvantages of JavaScript like Typescript is designed to
handle the needs of complex programs.
 Typescript was debuted as a beta programming language on October 1, 2012
and since then has gone through many versions with improved capabilities.
 Another key feature of Typescript is in version Typescript 2.6 that covers error
suppression comments.
 Typescript is more predictable and is generally easier to debug.

4) List some benefits of using Typescript?

Following are some benefits of using Typescript

1. One of the biggest advantages of Typescript is its code completion and


intelligence.
2. It provides the benefits of optional static typing .Here Typescript provides types
that can be added to variables, functions, properties etc.
3. Typescript has the ability to compile down to a version of JavaScript that runs on
all browsers.
4. Typescript tries to extend JavaScript. Compiler generates JavaScript.
5. Typescript is a backward compatible version of JavaScript that compiles to pure
JavaScript which makes their writing easier and faster.
6. Typescript is purely object oriented programming which means it is a
programming paradigm based on the concepts of objects.
7. Most important advantage is it offers a “compiler” that can convert to JavaScript
equivalent code. And it has a concept of namespace defined by a “module”.

5) List the built-in types in Typescript?

These are also called the primitive types in Typescript. These are of 5 types: –
1. Number type: it is used to represent number type values and represents double
precision floating point values.

Syntax- var variable_name: number;

2. String type: it represents a sequence of characters stored as Unicode UTF-16


code. It is the same as JavaScript primitive type.

Syntax- var variable_name: string;

3. Boolean type: in Typescript, it is used to represent a logical value. When we use


the Boolean type, we get output only in true or false. It is also the same as
JavaScript primitive type.

Syntax- var variable_name: bool;

4. Null type: it represents a null literal and it is not possible to directly reference the
null type value itself.

Syntax- var variable_name:number=null;

5. Undefined type: it is the type of undefined literal. This type of built-in type is the
sub-type of all the types.

Syntax- var variable_name:number=undefined;

6) How to compile a Typescript file?

A Typescript file is used to write more manageable and complex code in AppBuilder but
before that, they need to be compiled to JavaScript. Here are the steps which are
followed while compiling a Typescript file to JavaScript: –

1. It should be firstly verified that the Typescript engine has been enabled or not. In
the title bar, click your username and select options.
2. In the project navigator, select and right-click the TS files that are to be compiled.
3. Choose compile to JavaScript.
4. Add a <script> reference for the JS file in the HTML code if needed.
5. To compile a typescript file via command line tsc <TypeScript File
Name> command is used.
7) What are Modules in Typescript?

Modules are powerful way to share code between files.By using modules effectively in
your project you can keep you file size small and dependencies clear.
Modules are executed within their own scope, not in the global scope; this means that
variables, functions, classes, etc. declared in a module are not visible outside the
module unless they are explicitly exported using one of the export forms.

Creating a Module

module module_name{

class xyz{
export foo(x, y){
return x*y;
}
}

8) What are Mixins in TypeScript?

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

9) Who developed Typescript and what is the current stable version of


Typescript?

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.

10) Tell the minimum requirements for installing Typescript. Also,


mention the steps involved in it.
Installing Typescript with the help of node and npm is recommended. Here, npm is used
to install all the libraries and tools. Typescript should be installed globally using
npm install –g typescript
It installs a command line code “tsc” which will further be used to compile your
Typescript code. Make sure that you check the version of Typescript installed on your
system.

Following steps are involved for installing Typescript on your system:

1. Download and run the .msi installer for node.


2. Enter the command “node –v” to check if the installation was successful.
3. Type the following command in the terminal window to install Typescript:

npm install –g typescript

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


Typescript?

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-

1. A variable name should contain alphabets and numeric digits.


2. It cannot contain spaces and special characters except underscore (_) and dollar
($) sign.
3. 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;

12) What do you mean by interfaces? Explain them with reference to


Typescript.

An interface is a syntactical contract which defines the syntax of any entity. Interfaces in
Typescript define properties, methods, and events which are the members of the
interface. It contains only the declaration of the members. It is responsible for deriving
classes to define the members. It often helps in providing a standard structure that the
deriving classes would follow. For declaring an interface, we make use of the “interface”
keyword.
Syntax-

interface interface_name{

Statements;

}
Interfaces need not to be converted to JavaScript for execution. They have zero runtime
JavaScript impact. Interfaces can define both the kind of keys which an array uses and
the type of entry it contains.

13) What do you understand by classes in Typescript? List some


features of classes.

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

14) Is Native Javascript supports modules?

Currently, Modules are not supported by Native JavaScript.To create and work with
modules in Javascript you require an external like CommonJS.
Looking For Angular 2 Interview Questions. Click here

15) How to compile multiple Typescript files into a single file?

Using below command we can compile multiple typescript files into a single file
tsc --outFile outputfile.ts file1.ts file2.ts file3.ts ... filen.ts

16) How to Call Base Class Constructor from Child Class in TypeScript?

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

17) What are Closures in Javascript?

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.

18) List types of scopes available in Javascript?

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

 Global Scope
 Local Scope

19) What is namespace in Typescript? How to declare a namespace in


Typescript?

Internal Modules are known as namespaces in Typescript.Namespaces are used to


maintain the legacy code of typescript interally. A namespace is simply a way to
logically group related classes or interfaces in a wrapper.
Synatax for creating namespace in Typescript
namespace YourNameSpace {
export class Class1 { }
export class Class2 { }
}

20) Explain Decorators in Typescript? List type of Decorators available


in Typescript?
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

21) What is default visibility for properties/methods in Typescript


classes?

Public is default visibility for properties/methods in Typescript classes

22) Explian Type assertions in TypeScript?

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.

23) What is an Interface in TypeScript?

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

24) What are TypeScript Optional Properties?

The optional properties use as an optional thing. The interface typescript has many
properties but every property not required. You can pass the object into interface using (
? ) question mark symbol.

25) What is an implicit Module in Typescript?


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.

26) What is duck typing in TypeScript?

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.

1) What is Typescript?
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?


TypeScript is different from JavaScript in the following manner:
SN JavaScript TypeScript

1 It was developed by Netscape in 1995. It was developed by Anders Hejlsberg in 2012.

2 JavaScript source file is in ".js" extension. TypeScript source file is in ".ts" extension.

3 JavaScript doesn't support ES6. TypeScript supports ES6.

4 It doesn't support strongly typed or static It supports strongly typed or static typing feature.
typing.

5 It is just a scripting language. It supports object-oriented programming concept like


classes, interfaces, inheritance, generics, etc.

6 JavaScript has no optional parameter TypeScript has optional parameter feature.


feature.

7 It is interpreted language that's why it It compiles the code and highlighted errors during the
highlighted the errors at runtime. development time.

8 JavaScript doesn't support modules. TypeScript gives support for modules.

9 In this, number, string are the objects. In this, number, string are the interface.

10 JavaScript doesn't support generics. TypeScript supports generics.

3) Why do we need TypeScript?


We need TypeScript:
o TypeScript is fast, simple, and most importantly, easy to learn.

o TypeScript supports object-oriented programming features such as classes,


interfaces, inheritance, generics, etc.
o 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.
o TypeScript supports all JavaScript libraries because it is the superset of
JavaScript.
o TypeScript support reusability by using the inheritance.

o TypeScript make app development quick and easy as possible, and the tooling
support of TypeScript gives us autocompletion, type checking, and source
documentation.
o TypeScript supports the latest JavaScript features including ECMAScript 2015.

o TypeScript gives all the benefits of ES6 plus more productivity.

o TypeScript supports Static typing, Strongly type, Modules, Optional Parameters,


etc.

4) List some features of Typescript?


5) List some benefits of using Typescript?
TypeScript has the following benefits.

o It provides the benefits of optional static typing. Here, Typescript provides types
that can be added to variables, functions, properties, etc.
o Typescript has the ability to compile down to a version of JavaScript that runs on
all browsers.
o TypeScript always highlights errors at compilation time during the time of
development whereas JavaScript points out errors at the runtime.
o TypeScript supports strongly typed or static typing whereas this is not in
JavaScript.
o It helps in code structuring.

o It uses class-based object-oriented programming.

o It provides excellent tooling supports with IntelliSense which provides active


hints as the code is added.
o It has a namespace concept by defining a module.

6) What are the disadvantages of TypeScript?


TypeScript has the following disadvantages:

o TypeScript takes a long time to compile the code.

o TypeScript does not support abstract classes.

o If we run the TypeScript application in the browser, a compilation step is


required to transform TypeScript into JavaScript.
o Web developers are using JavaScript from decades and TypeScript doesn?t bring
anything new.
o To use any third party library, the definition file is must. And not all the third
party library have definition file available.
o 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?
The TypeScript has mainly three components. These are-

Language

The language comprises elements like new syntax, keywords, type annotations, and
allows us to write TypeScript.

Compiler

The TypeScript compiler is open source, cross-platform, and is written in TypeScript. It


transforms the code written in TypeScript equivalent to its JavaScript code. It performs
the parsing, type checking of our TypeScript code to JavaScript code. It can also help in
concatenating different files to the single output file and in generating source maps.

Language Service

The language service provides information which helps editors and other tools to give
better assistance features such as automated refactoring and IntelliSense.
8) Who developed Typescript and what is the current
stable version of Typescript?
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?
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:

1. Download and run the .msi installer for the node.

2. Enter the command "node -v" to check if the installation was successful.

3. Type the following command in the terminal window to install Typescript: $ npm
install -g typescript
10) List the built-in types in Typescript.
The built-in data types are also known as primitive data types in Typescript. These are
given below.

Number type: It is used to represent number type values. All the numbers in
TypeScript are stored as floating point values.

Syntax: let identifier: number = value;

String type: It represents a sequence of characters stored as Unicode UTF-16 code.


We include string literals in our scripts by enclosing them in single or double quotation
marks.

Syntax: let identifier: string = " ";

Boolean type: It is used to represent a logical value. When we use the Boolean type,
we get output only in true or false. A Boolean value is a truth value that specifies
whether the condition is true or not.

Syntax: let identifier: bool = Boolean value;

Null type: Null represents a variable whose value is undefined. It is not possible to
directly reference the null type value itself. Null type is not useful because we can only
assign a null value to it.
Syntax: let num: number = null;

Undefined type: It is the type of undefined literal. The Undefined type denotes all
uninitialized variables. It is not useful because we can only assign an undefined value to
it. This type of built-in type is the sub-type of all the types.

Syntax: let num: number = undefined;

Void type: A void is the return type of the functions that do not return any type of
value. It is used where no datatype is available.

Syntax: let unusable: void = undefined;

11) What are the variables in Typescript? How to


create a variable in Typescript?
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-

o The variable name must be an alphabet or numeric digits.

o The variable name cannot start with digits.

o 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:

1. Declare type and value in a single statement. Syntax: var [identifier] : [type-
annotation] = value;

2. Declare type without value. Syntax: var [identifier] : [type-annotation];

3. Declare its value without type. Syntax: var [identifier] = value;

4. Declare without value and type. Syntax: var [identifier];


12) How to compile a Typescript file?
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?
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?
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.
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.
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-

1. Inheritance

2. Encapsulation

3. Polymorphism

4. Abstraction

17) Is Native Javascript supports modules?


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?
TypeScript supports following object oriented terms.

o Modules

o Classes
o Interfaces

o Inheritance

o Data Types

o Member functions

19) How to Call Base Class Constructor from Child


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

20) How do you implement inheritance in


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


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?
The difference between internal and external module is given below:
SN Internal Module External Module

1 Internal modules were used to External modules are useful in


logically group the classes,
hiding the internal statements of the module.
interfaces, functions, variables into a
single unit and can be exported in definitions and show
another module.
only the methods and parameters

associated with the declared variable.

2 Internal modules were in the earlier External modules are simply known as a module in the
version of Typescript. But they are
latest version of TypeScript.
still supported by using namespace in
the latest version of TypeScript.

3 Internal modules are local or External modules are separately loaded


exported members of other modules
bodies of code referenced using external module names.
(including the global module and
external modules).

4 Internal modules are declared using An external module is written as a


ModuleDeclarations that specify their
separate source file that contains
name and body.
at least one import or export

declaration.

5 Example: Example:

module Sum { export class Addition{


export function add(a, b) { constructor(private x?: number,
console.log("Sum: " + private y?: number){
(a+b)); }
} Sum(){
} console.log
("SUM: " +(this.x + this.y));
}
}

23) What is namespace in Typescript? How to


declare a namespace in Typescript?
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.

Note: A namespace can be defined in multiple files and allow to


keep each file as they were all defined in one place. It makes
code easier to maintain.

Synatax for creating namespace

namespace <namespace_name> {
export interface I1 { }
export class c1{ }
}
24) Explain Decorators in Typescript?
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?


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

Note: Optional parameters must follow the required parameters.


If we want to make arg1 optional, instead of arg2, then we
need to change the order and arg1 must be put after arg2.
function Demo(arg2: number, arg1? :number) {
}

28) Does TypeScript supports function overloading


as JavaScript doesn't support function overloading?
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?


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


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

tsc --declaration file1.ts

33) What is tsconfig.json file?


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?


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?
Yes, TypeScript support all object-oriented principles. There are four main principles to
object-oriented programming:

1. Encapsulation,
2. Inheritance,

3. Abstraction, and

4. Polymorphism.

36) How to check null and undefined in TypeScript?


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
"a == null"
"a is undefined"
"b == null"
"b === null"

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


how?
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.

o Install Typescript compiler

npm i -g typescript

o 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"
}
}

o Compile ts files

tsc

o Run

node build/index.js
38) What is the difference between "interface vs
type" statements?

interface X {
a: number
b: string
}
type X = {
a: number
b: string
};

S interface type
N

1 An interface declaration always A type alias declaration can introduce a name for any kind of
introduces a named object type. type, including primitive, union, and intersection types.

2 An interface can be named in an Type alias for an object type literal cannot be named in an
extends or implements clause. extends or implements clause.

3 Interfaces create a new name Type aliases don't create a new name.
that is used everywhere.

4 An interface can have multiple Type alias for an object type literal cannot have multiple
merged declarations. merged declarations.

39) What are Ambients in TypeScripts and when to


use them?
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?

o TypeScript Map file is a source map file which holds information about our
original files.
o .map files are source map files that let tools map between the emitted JavaScript
code and the TypeScript source files that created it.
o 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?


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?


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?


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.

o Name the files with a .tsx extension

o Enable the jsx option

44) What is Rest parameters?


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:

o Only one rest parameter is allowed in a function.

o It must be an array type.

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


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.

Non-Relative Relative

A non-relative import can be resolved relative to baseUrl, Relative imports can be used for our
or through path mapping. In other words, we use non- own
relative paths when importing any of our external modules that are guaranteed to
dependencies. maintain
Example: their relative location at runtime.
import * as $ from "jquery"; A relative import is starts with /, ./ or
import { Component } from "@angular/core"; ../.
Example:
import Entry from
"./components/Entry";
import {DefaultHeaders} from
"../constants/http";

47) What is an anonymous function?


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?


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;
}

Note: Not all merges are allowed in TypeScript. Currently, classes can not merge with other
classes or variables.

49) What are method overriding in TypeScript?


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


o The method must have the same name as in the parent class

o The method must have the same parameter as in the parent class.

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


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.
1. What are the main features of TypeScript?

 Cross-Platform: The TypeScript compiler can be installed on any


operating system such as Windows, macOS, and Linux.
 ES6 Features: TypeScript includes most features of planned
ECMAScript 2015 (ES6) such as Arrow functions.
 Object-Oriented Language: TypeScript provides all the
standard OOP features like classes, interfaces, and modules.
 Static Type-Checking: TypeScript uses static typing and helps type
checking at compile time. Thus, you can find compile-time errors while
writing the code without running the script.
 Optional Static Typing: TypeScript also allows optional static typing
in case you are used to the dynamic typing of JavaScript.
 DOM Manipulation: You can use TypeScript to manipulate the DOM
for adding or removing client-side web page elements.

2. What are the benefits of using TypeScript?

 TypeScript is more expressive, meaning it has less syntactical clutter.


 Easy debugging due to advanced debugger that focuses on catching
logical errors before compile-time
 Static typing makes TypeScript easier to read and more structured
than JavaScript’s dynamic typing.
 Usable across platforms, in both client and server-side projects due
to versatile transpiling.

3. What are the built-in data types of TypeScript?

Number type: It is used to represent number type values. All the numbers in
TypeScript are stored as floating-point values.

let identifier: number = value;


String type: It represents a sequence of characters stored as Unicode UTF-16
code. Strings are enclosed in single or double quotation marks.

let identifier: string = " ";

Boolean type: a logical binary switch that holds either true or false

let identifier: bool = Boolean value;

Null type: Null represents a variable whose value is undefined.

let num: number = null;

Undefined type: an undefined literal that is the starting point of all


variables.

let num: number = undefined;

Void type: The type assigned to methods that have no return value.

let unusable: void = undefined;

4. What is the current stable version of TypeScript?

The current stable version is 4.2.3.

5. What is an interface in TypeScript?

Interfaces define a contract or structure for objects that use that interface.

An interface is defined with the keyword interface and it can include properties
and method declarations using a function or an arrow function.

interface IEmployee {
empCode: number;
empName: string;
getSalary: (number) => number; // arrow function
getManagerName(number): string;
}

6. What are modules in TypeScript?

Modules in TypeScript are a collection of related variables, functions, classes,


and interfaces.

You can think of modules as containers that contain everything needed to


execute a task. Modules can be imported to easily share code between projects.

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

7. How can you use TypeScript for the backend?

You can use Node.js with TypeScript to bring the benefits of TypeScript to
backend work.

Simply install the TypeScript compiler into your Node.js by entering the
following command:

npm i -g typescript

8. What are Type assertions in TypeScript?

Type assertion in TypeScript works like typecasting in other languages but


without the type checking or restructuring of data possible in languages like
C# and Java. Type assertion has no impact on runtime and is used purely by
the compiler.

Type assertion is essentially a soft version of typecasting that suggests the


compiler see the variable as a certain type but does not force it into that mold
if it’s in a different form.

TypeScript Syntax & Language Basics

9. How do you create a variable in TypeScript?

You can create variables in three ways: var, let, and const. var is the old style of
fiercely scoped variables. You should avoid using var whenever possible
because it can cause issues in larger projects.

var num:number = 1;

let is the default way of declaring variables in TypeScript, Compared


to var, let reduces the number of compile-time errors and increases code
readability.

let num:number = 1;

constcreates a constant variable whose value cannot change. It uses the same
scoping rules as let and helps reduce overall program complexity.

const num:number = 100;

10. How do you call a base class constructor from a child class in
TypeScript?
You can use the super() function to call the constructor of the base class.

class Animal {
name: string;
constructor(theName: string) {
this.name = theName;
}
move(distanceInMeters: number = 0) {
console.log(`${this.name} moved ${distanceInMeters}m.`);
}
}

class Snake extends Animal {


constructor(name: string) {
super(name);
}
move(distanceInMeters = 5) {
console.log("Slithering...");
super.move(distanceInMeters);
}
}

11. Explain how to use TypeScript Mixins.

Mixins are essentially inheritance that works in the opposite direction. Mixins
allow you to build new classes by combining simpler partial class setups from
previous classes.

Instead of class A extending class B to gain its functionality, class B takes from
class A and returns a new class with additional functionality.

12. How do you check null and undefined in TypeScript?

You can either use a juggle-check, which checks both null and undefined, and
strict-check which returns true for values set to null and won’t evaluate true
for undefined variables.
//juggle
if (x == null) {
}

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');

13. What are getters/setters in TypeScript? How do you use them?

Getters and setters are special types of methods that help you delegate
different levels of access to private variables based on the needs of the
program.

Getters allow you to reference a value but cannot edit it. Setters allow you to
change the value of a variable but not see its current value. These are essential
to achieve encapsulation.

For example, a new employer may be able to get the number of employees in
the company but does not have permission to set the number of employees.

const fullNameMaxLength = 10;

class Employee {
private _fullName: string = "";

get fullName(): string {


return this._fullName;
}

set fullName(newName: string) {


if (newName && newName.length > fullNameMaxLength) {
throw new Error("fullName has a max length of " + fullNameMaxLength);
}

this._fullName = newName;
}
}

let employee = new Employee();


employee.fullName = "Bob Smith";

if (employee.fullName) {
console.log(employee.fullName);
}

14. How do you allow classes defined in a module to be accessible outside of a


module?

You can use the export keyword to open modules up for use outside the
module.

module Admin {
// use the export keyword in TypeScript to access the class outside
export class Employee {
constructor(name: string, email: string) { }
}
let alex = new Employee('alex', '[email protected]');
}

// The Admin variable will allow you to access the Employee class outside the module
with the help of the export keyword in TypeScript
let nick = new Admin.Employee('nick', '[email protected]');

15. How do we convert string to a number using Typescript?


Similar to JavaScript, You can use the parseInt or parseFloat functions to
convert a string to an integer or float, respectively. You can also use the unary
operator + to convert a string to the most fitting numeric type, “3” becomes the
integer 3 while “3.14” becomes the float 3.14.

var x = "32";
var y: number = +x;

16. What is a ‘.map’ file, and why/how can you use it?

A map file is a source map that shows how the original TypeScript code was
interpreted into usable JavaScript code. They help simplify debugging because
you can catch any odd compiler behavior.

Debugging tools can also use these files to allow you to edit the underlying
TypeScript rather than the emitted JavaScript file.

17. What are classes in TypeScript? How do you define them?

Classes represent the shared behaviors and attributes of a group of related


objects.

For example, our class might be Student which all have the attendClass method.
On the other hand, John is an individual instance of type Student and may have
additional unique behaviors like attendExtracurricular.

You declare classes using the keyword class:

class Student {
studCode: number;
studName: string;
constructor(code: number, name: string) {
this.studName = name;
this.studCode = code;
}
18. How does TypeScript relate to JavaScript?

TypeScript is an open-source syntactic superset of JavaScript that compiles to


JavaScript. All original JavaScript libraries and syntax still works but
TypeScript adds additional syntax options and compiler features not found in
JavaScript.

TypeScript can also interface with most of the same technologies as


JavaScript, such as Angular and jQuery.

19. What is JSX in TypeScript?

JSX is an embeddable XML-like syntax that allows you to create HTML.


TypeScript supports embedding, type checking, and compiling JSX directly to
JavaScript.

20. What are the JSX modes TypeScript supports?

TypeScript has built-in support for preserve, react, and react-native.

 preserve keeps the JSX intact for use in a subsequent transformation.


 react does not go through a JSX transformation and instead
emits react.createElement and outputs as a .js file extension.
 react-native combines preserve and react in that it maintains all JSX
and outputs as a .js extension.

21. How do you compile a TypeScript file?

You need to call the TypeScript compiler tsc to compile a file. You’ll need to
have the TypeScript compiler installed, which you can do using npm.
npm install -g typescript
tsc <TypeScript File Name>

22. What scopes are available in TypeScript? How does this compare to JS?

 Global Scope: defined outside of any class and can be used anywhere
in the program.
 Function/Class Scope: variables defined in a function or class can be
used anywhere within that scope.
 Local Scope/Code Block: variables defined in the local scope can be
used anywhere in that block.

Advanced TypeScript Questions

23. What are Arrow/lambda functions in TypeScript?

Fat arrow function is a shorthand syntax for defining function expressions of


anonymous functions. It’s similar to lambda functions in other languages. The
arrow function lets you skip the function keyword and write more concise code.

24. Explain Rest parameters and the rules to declare Rest parameters.

Rest parameters allow you to pass a varied number of arguments (zero or


more) to a function. This is useful when you’re unsure how many parameters a
function will receive. All arguments after the rest symbol ... will be stored in
an array. For example:

function Greet(greeting: string, ...names: string[]) {


return greeting + " " + names.join(", ") + "!";
}
Greet("Hello", "Steve", "Bill"); // returns "Hello Steve, Bill!"

Greet("Hello");// returns "Hello !"

The rest parameter must be the last on parameter definition and you can only
have 1 rest parameter per function.

25. What are Triple-Slash Directives? What are some of the triple-slash
directives?

Triple-slash Directives are single-line comments that contain an XML tag to


use as compiler directives. Each directive signals what to load during the
compilation process. Triple-slash Directives only work at the top of their file
and will be treated as normal comments anywhere else in the file.

 /// <reference path="..." /> is the most common directive and


defines the dependency between files.
 /// <reference types="..." /> is similar to path but defines a
dependency for a package.
 /// <reference lib="..." /> allows you to explicitly include the built-
in lib file.

26. What does the Omit type do?


is a form of utility type, which facilitates common type transformations.
Omit
Omit lets you construct a type by passing a current Type and selecting Keys to be
omitted in the new type.

Omit<Type, Keys>

For example:

interface Todo {
title: string;
description: string;
completed: boolean;
createdAt: number;
}

type TodoPreview = Omit<Todo, "description">;

27. How do you achieve function overloading in TypeScript?

To overload, a function in TypeScript, simply create two functions of the same


name but have different argument/return types. Both functions must accept
the same number of arguments. This is an essential part of polymorphism in
TypeScript.

For example, you could make an add function that sums the two arguments if
they’re numbers and concatenates them if they’re strings.

function add(a:string, b:string):string;

function add(a:number, b:number): number;

function add(a: any, b:any): any {


return a + b;
}

add("Hello ", "Steve"); // returns "Hello Steve"


add(10, 20); // returns 30

28. How do you make all properties of an interface optional?

You can use the partial mapped type to easily make all properties optional.

29. When should you use the ‘unknown’ keyword?

You should use unknown if you don’t know which type to expect upfront but
want to assign it later on, and the any keyword will not work.
30. What are decorators, and what can they be applied to?

A decorator is a special kind of declaration that lets you modify classes or class
members all at once by marking them with the @<name> annotation. Each
decorator must refer to a function that’ll be evaluated at runtime.

For example, the decorator @sealed would correspond to the sealed function.
Anything marked with @sealed would be used to evaluate the sealed function.

function sealed(target) {
// do something with 'target' ...
}

They can be attached to:

 Class declarations
 Methods
 Accessors
 Properties
 Parameters
Decorators are not enabled by default. To enable them, you have to edit
the experimentalDecorators field in the compiler options from
your tsconfig.json file or the command line.

Q1. What is TypeScript? Why should we use it?

TypeScript is a typed superset of JavaScript that compiles to plain


JavaScript which runs on any browser or JavaScript engine.
TypeScript offers support for the latest JavaScript features and
also has some additional features like static typing, object oriented
programming and automatic assignment of constructor.

Q2. What are Types in TypeScript?

The type represents the type of the value we are using in our
programs. TypeScript supports simplest units of data such as
numbers, strings, boolean as well as additional types like enum,
any, never.

In TypeScript, we are declaring a variable with its type explicitly by


appending the : with the variable name followed by the type.

The reason adding types are:

 Types have proven ability to enhance code quality and


understandability.
 It’s better for the compiler to catch errors than to have things
fail at runtime.

 Types are one of the best forms of documentation we can have.

Q3. What is Type assertions in TypeScript?

A type assertion is like a type cast in other languages, but performs


no special checking or restructuring of data. It has no runtime
impact, and is used purely by the compiler. TypeScript assumes
that we have performed any special checks that we need.

Q4. What is as syntax in TypeScript?

The as is additional syntax for Type assertion in TypeScript. The


reason for introducing the as-syntax is that the original syntax
(<type>) conflicted with JSX.

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


allowed.
Q5. What is Compilation Context?

The compilation context is basically grouping of the files that


TypeScript will parse and analyze to determine what is valid and
what isn’t. Along with the information about which files, the
compilation context contains information about which
compiler options. A great way to define this logical grouping is
using a tsconfig.json file.

A tsconfig.json might look like the following snippet:


Q6. Can an interface extends a class just like
a classimplements interface?

Yes, an interface extends a class, when it does it inherits the


members of the class but not their implementations. Interfaces
inherit even the private and protected members of a base class.
This means that when you create an interface that extends a class
with private or protected members, that interface type can only be
implemented by that class or a subclass of it.

Q7. What are all the other access modifiers that


TypeScript supports?

TypeScript supports access


modifiers public, private and protected which determine the
accessibility of a class member as given below:

 public - All the members of the class, its child classes, and the
instance of the class can access.

 protected - All the members of the class and its child classes can
access them. But the instance of the class can not access.

 private - Only the members of the class can access them.

If an access modifier is not specified it is implicitly public as that


matches the convenient nature of JavaScript.
Also note that at runtime (in the generated JS) these have no
significance but will give you compile time errors if you use them
incorrectly.

Q8. What is Contextual typing?

TypeScript compiler can figure out the type if you have types on
one side of the equation but not the other. For example, we can re-
write the previous example function as follow:

Note that we can omit the typings on the right side of the equal
since it can be figured out automatically by TypeScript. This helps
cut down on the amount of effort to keep our program typed.

Q9. What is Generic Class?

A generic class has a similar shape to a generic interface. Generic


classes have a generic type parameter list in angle brackets (<>)
following the name of the class.
Q10. Explain Relative vs. Non-relative module imports.

Module imports are resolved differently based on whether the


module reference is relative or non-relative.

A relative import is one that starts with /, ./ or ../. Some


examples include:

 import Entry from "./components/Entry";

 import { DefaultHeaders } from "../constants/http";

Any other import is considered non-relative. Some examples


include:
 import * as $ from "jquery";

 import { Component } from "@angular/core";

A relative import is resolved relative to the importing file and


cannot resolve to an ambient module declaration. We should use
relative imports for our own modules that are guaranteed to
maintain their relative location at runtime.

A non-relative import can be resolved relative to baseUrl, or


through path mapping.

Q11. What is Triple-Slash Directive? What are some of


the triple-slash directives?

Triple-slash directives are single-line comments containing a


single XML tag. The contents of the comment are used as compiler
directives.

Triple-slash directives are only valid at the top of their containing


file. A triple-slash directive can only be preceded by single or
multi-line comments, including other triple-slash directives. If
they are encountered following a statement or a declaration they
are treated as regular single-line comments, and hold no special
meaning. Below are some of the triple-slash directives in
TypeScript:
 The /// <reference path="..." /> directive is the most common
of this group. It serves as a declaration of dependency between
files. Triple-slash references instruct the compiler to include
additional files in the compilation process. If the compiler
flag --noResolve is specified, triple-slash references are ignored;
they neither result in adding new files, nor change the order of
the files provided.

 Similar to a /// <reference path="..." /> directive, this


directive serves as a declaration of dependency; a ///
<reference types="..." /> directive, however, declares a

dependency on a package. For example, including ///


<reference types="node" /> in a declaration file declares that

this file uses names declared in @types/node/index.d.ts; and


thus, this package needs to be included in the compilation
along with the declaration file.

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

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.

In order to use JSX in our file: we must name our file with
a .tsx extension and should enable jsx option.
Q13. What are all the JSX modes TypeScript supports?

TypeScript ships with three JSX modes: preserve, react, and react-
native.

The preserve mode will keep the JSX as part of the output to be
further consumed by another transform step (e.g. Babel).
Additionally the output will have a .jsx file extension.
The react mode will emit React.createElement, does not need to go
through a JSX transformation before use, and the output will have
a .js file extension. The react-native mode is the equivalent of
preserve in that it keeps all JSX, but the output will instead have
a .js file extension.

Q14. Why TypeScript is referred as Optionally Statically


Typed Language?

TypeScript is referred as optionally statically typed, which means


we can make the compiler to ignore the type of a variable
optionally. Using any data type, we can assign any type of value to
the variable. TypeScript will not give any error checking during
compilation.
Q15. What is TypeScript Definition Manager?

When using TypeScript, you will need TypeScript definition files to


work with external libraries. TypeScript Definition Manager (TSD)
is a package manager to search and install TypeScript definition
files directly from the community
driven DefinitelyTyped repository.

Consider we need typings file for jQuery so that we can use jQuery
with TypeScript. This command, tsd query jquery --action
install (we need to have tsdinstalled), finds and install the typings

file for jQuery. Now we can include the below directive at the top of
the file where we want to use jQuery.

TSD is now offically deprecated, and we should


use typings instead.
Q1) Explain what is Typescript, and how is it different from
JavaScript?
Answer:

Typescript is a superscript of JavaScript and is used for the development of large

applications. It provides optional static typing, classes, and interfaces. It can be said as

a language and also a set of tools. It helps developers to use highly productive tools

and helps in code refactoring. The main differences between Typescript and

JavaScript are:

Typescript supports classes that help the programmer work more in an object-oriented

way, while JavaScript uses reusable components with functions and prototype-based

inheritance. JavaScript does not have any interfaces; on the other hand, typescript has

interfaces. Static typing is supported in Typescript, while it is not supported in

JavaScript. Typescript provides optional parameters; JavaScript does not.

Q2) Which are different data types that are supported by


Typescript and explain how to implement inheritance?
Answer:

Typescript also supports data types provided by all other languages. It includes:

 Boolean: This can have values as true or false

 Number: This can be any number value

 String: This can be any character value


 Array: This can be a list of numbers together

 Enum: This allows for creating a user-defined data type.

Inheritance can be implemented in Typescript by using the extends keyword.

class Car {
public domestic:boolean;
constructor(public name: string) { }
}
class SUV extends Car {
constructor(name: string, domestic: boolean)
{
super(name);
this.domestic = true;
}
}
class Sedan extends Car {
constructor(name: string, domestic: boolean)
{
super(name);
this.domestic = false;
}
}

Q3) Explain the tsconfig.json file?


Answer:

This file is used to indicate that the directory is the root of the Typescript project. This

file specifies that root files and compiler options are required to compile that

particular project. This file can also be used to streamline the building of the project.

Below sample can be taken as an example:


{

"compilerOptions": {

"removeComments": true,

"sourceMap": true

},

"files": [

"main.ts",

"othermodule.ts"

] }

Q4) Explain Lambda/Arrow functions in Typescript?


Answer:

The arrow function acts like an additional feature in typescript and is also known as

the lambda function. This function is without a name.

var mulNum = (n1: number, n2: number) => n1 * n2;

In this example, => is a lambda operator and (n1 * n2) is the body of function and

n1,n2 are the parameters.


let addNum = (n1: number, n2: number): number => { return

n1 + n2; }

let multiNum = (n1: number, n2: number): number =>

{ return n1 * n2; }

let dividNum = (n1: number, n2: number): number =>

{ return n1 / n2; }

addNum(10, 2);// Result - 12

multiNum(10, 2);// Result - 20

multiNum(10, 2);// Result – 5

Q5) What is the Anonymous function?


Answer:

This function is declared without any named identifier to refer to it.

var anonyFunc = function (num1: number, num2: number):

number {

return num1 + num2;

//RESULT
console.log(anonyFunc(10, 20)); //Return is 30

//RESULT

console.log(anonyFunc(10, "xyz"));

// error: This will throw an error as string is passed

instead of an integer.

Q6) how can a class defined in a module be used outside the module?
Answer:

Classes defined in a module are available within the module and cannot be accessed

outside the module.

module Vehicle {

class Car {

constructor (

public make: string,

public model: string) { }

var audiCar = new Car("Audi", "Q7");

}
var fordCar = Vehicle.Car("Ford", "Figo");

The variable fordCar will give an error as the class Car

is not accessible and the user needs to use export

keyword for the classes.

module Vehicle {

export class Car {

constructor (

public make: string,

public model: string) { }

var audiCar = new Car("Audi", "Q7");

var fordCar = Vehicle.Car("Ford", "Figo");

This variable will now work as export is used to make the Car accessible outside its

module.
Q7) What are decorators, and list some of the decorators in
TypeScript?
Answer:

Decorators enable a user to modify a class and its members. It allows the user to add

annotations and Metaprogramming syntax for carrying out class declarations and

members. These were just released on an experimental basis. Decorators can be

enabled using a command line or by editing the tsconfig.json file. To enable

decorators using command line following command should be used:

tsc --target ES5 --experimentalDecorators

Q8) How to compile a Typescript file?


Answer:

The following steps should be followed in order to compile a typescript file:

 A user must check if the Typescript engine is enabled or not. A user can go to

the title bar and check for their username, and select options.

 In the project navigator, select and right-click the TS files that are to be

compiled.

 Select compile to JavaScript

 A user can add a script reference to this compiled Javascript file in HTML

code.
 Once this is done, the user can go to command line tsc <TypeScript File

Name> to compile.

Let us move to the next Typescript Interview Questions.

Q9) What are the Interfaces in Typescript?


Answer:

The interface defines the syntax of any variable or entity. Interfaces define properties,

methods, and various events. Here only members are declared. Interfaces help define

various members and help in defining a structure for the deriving classes. Interfaces

can be declared using the interface keyword.

Q10) Why is typescript called an optionally statically typed


language?
Answer:

Typescript being optionally statically typed language means that compiler can ignore

the type of variable. Using ‘any’ datatype user can assign any type of variable.

Typescript will not throw any error.

var unknownType: any = 4;

unknownType = "Okay, I am a string";

unknownType = false; // A boolean.


Using this, any data type can be declared.

1 — What does the ‘Omit’ type do?

Answer: It’s a new type where you can define some properties to
be excluded from the original type.

Example:
type Person = { name: string; age: number; location: string; };type
QuantumPerson = Omit<Person, 'location'>; // Same as next line
QuantumPerson = { name: string; age: number; };

2 — When to use the ‘declare’ keyword?

Answer: When using a JavaScript library which doesn’t have


declarations, inside your TypeScript project.

Example:
declare const libraryName;

3 — How to get automatically ‘declaration’ files?

Answer: Set the declaration compiler option on true in


the tsconfig.json .

Example:
{
"compilerOptions": {
...
"declaration": true,
}
}
4 — How to overload a function?

Answer: Use the same function name again above the original
function without the brackets {}. Change the number of
arguments, the arguments types or/and the return type.

Example:
function add(x: string, y: string): string;
function add(x: number, y: number): number {
return x + y;
}

5 — How to easily make all properties of an


interface optional?

Answer: Use the Partial mapped type.

Example:
interface Person {
name: string;
age: number;
}type PartialPerson = Partial<Person>; // Same as next
linesinterface PartialPerson {
name?: string;
age?: number;
}

6 — Where can decorators be applied to?

Answer: Classes, properties, methods, and method arguments.


Example:
@MyClassDecorator
export class Person { ...
@MyPropertyDecorator myProperty: string;
}

7 — What does the ‘Record’ type do?

Answer: It allows you to create a typed map .

Example:
let Person = Record<string, number> = {};
Person.age = 25;

8 — How can you access classes outside the


module they are defined in?

Answer: Use the export keyword in front of the class.

Example:
export class Person {}

9— When to use the ‘unknown’ keyword?

Answer: When you don’t want to use the any keyword or/and
don’t know the exact type up front but want to assign it later on.

Example:
let person: unknown = 'John';if (typeof person === string) {
let name: string = person;
}

10—What is a ‘.map’ file, and why/how can you use


it?

Answer: The map file is a source map file that can be used when
you want to debug. It can be generated by setting
the sourceMap compiler option on true in the tsconfig.json .

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

Q1:
Explain generics in TypeScript
Generics are able to create a component or function to work over a variety of types rather than a
single one.

/** A class definition with a generic parameter */


class Queue<T> {
private data = [];
push = (item: T) => this.data.push(item);
pop = (): T => this.data.shift();
}

const queue = new Queue<number>();


queue.push(0);
queue.push("1"); // ERROR : cannot push a string. Only numbers allowed

Q2:
What is TypeScript and why would I use it in place of JavaScript?

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.

In details:

 TypeScript supports new ECMAScript standards and compiles them to (older) ECMAScript
targets of your choosing. This means that you can use features of ES2015 and beyond, like
modules, lambda functions, classes, the spread operator, destructuring, today.
 JavaScript code is valid TypeScript code; TypeScript is a superset of JavaScript.
 TypeScript adds type support to JavaScript. The type system of TypeScript is relatively rich
and includes: interfaces, enums, hybrid types, generics, union and intersection types, access
modifiers and much more. TypeScript makes typing a bit easier and a lot less explicit by the
usage of type inference.
 The development experience with TypeScript is a great improvement over JavaScript. The
IDE is informed in real-time by the TypeScript compiler on its rich type information.
 With strict null checks enabled (--strictNullChecks compiler flag) the TypeScript compiler
will not allow undefined to be assigned to a variable unless you explicitly declare it to be of
nullable type.
 To use TypeScript you need a build process to compile to JavaScript code. The TypeScript
compiler can inline source map information in the generated .js files or create separate .map
files. This makes it possible for you to set breakpoints and inspect variables during runtime
directly on your TypeScript code.
 TypeScript is open source (Apache 2 licensed, see github) and backed by Microsoft. Anders
Hejlsberg, the lead architect of C# is spearheading the project.

Q3:
Could we use TypeScript on backend and how?

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.

1. Install the default Typescript compiler

npm i -g typescript

2. The TypeScript compiler takes options in the shape of a tsconfig.json file that determines
where to put built files and in general is pretty similar to a babel or webpack config.

{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"declaration": true,
"outDir": "build"
}
}
3. Compile ts files

tsc

4. Run

node build/index.js

Q4:
Does TypeScript support all object oriented principles?

The answer is YES. There are 4 main principles to Object Oriented Programming:

 Encapsulation,
 Inheritance,
 Abstraction, and
 Polymorphism.

TypeScript can implement all four of them with its smaller and cleaner syntax.

Q5:
How could you check null and undefined in TypeScript?
Just use:

if (value) {
}
It will evaluate to true if value is not:

 null
 undefined
 NaN
 empty string ''
 0
 false

TypesScript includes JavaScript rules.

Q6:
How to implement class constants in TypeScript?
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

Q7:
What is a TypeScript Map file?
.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 (e.g. Visual Studio or Chrome's dev tools)
can consume these files so you can debug the TypeScript file instead of the JavaScript file.

Q8:
What is getters/setters in TypeScript?

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)
Q9:
Are strongly-typed functions as parameters possible in TypeScript?
Problem

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.

Answer

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)

Q10:
Does TypeScript supports function overloading?

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());
}
}

Q11:
Explain how and why we could use property decorators in TS?
Answer

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() { }
}

Q12:
How can you allow classes defined in a module to accessible outside of the
module?

Classes 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 work
var 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 now
var fordCar = Vehicle.Car("Ford", "Figo");

Q13:
Is that TypeScript code valid? Explain why.
Problem

Consider:

class Point {
x: number;
y: number;
}

interface Point3d extends Point {


z: number;
}

let point3d: Point3d = {x: 1, y: 2, z: 3};

Answer

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.

Q14:
What are different components of TypeScript?
There are mainly 3 components of TypeScript .

1. Language – The most important part for developers is the new language. The language
consist of new syntax, keywords and allows you to write TypeScript.
2. 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.
3. Language Service – TypeScript language service which powers the interactive TypeScript
experience in Visual Studio, VS Code, Sublime, the TypeScript playground and other editor.

You might also like