Type Script
Type Script
Syntax:
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.
There are different reasons why a JavaScript developer should consider using
TypeScript. Some of them include:
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.
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.
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.
TypeScript is fast, simple, easy to learn and runs on any browser or JavaScript
engine.
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.
Web developers are using JavaScript for decades and TypeScript doesn’t bring
anything new.
The TypeScript Compiler − This compiler (tsc) converts the instructions written
in TypeScript to its JavaScript equivalent.
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.
There are two main ways to install TypeScript tools such as:
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.
tsc edureka.ts
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.
This will compile all 3 “.ts” file and output into a single “comman.js” file.
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.
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.
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.
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-
Yes, we can compile “.ts” automatically with real-time changes in the .ts file. This can
be done by using –watch compiler option:
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.
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.
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
Inheritance
Encapsulation
Polymorphism
Abstraction
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.
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:
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?
1 namespace <namespace_name> {
2 export interface I1 { }
3 export class c1{ }
}
4
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.
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
tsconfig.json
1 {
2 "compilerOptions": {
3 "target": "ES5",
4 "experimentalDecorators": true
}
5
}
6
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.
Example:
In the above example, arg1 is always required, and arg2 is an optional parameter.
The scope is a set of objects, variables, and function and the JavaScript can have a
global scope variable and local scope variable.
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
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.
//# sourceMappingURL=file1.js.map
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:
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.
The steps involved in the process of including the Type Definition File are:
$ tsd init
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.
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:
Example:
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.
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
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:
Interface Type
If you want to use JSX in your file, you need to name your file with a .tsx extension and
enable jsx option.
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.
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.
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:
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.
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
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:
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
Relative Non-Relative
Example:
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.
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.
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:
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.
1) What is 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.
4. Null type: it represents a null literal and it is not possible to directly reference the
null type value itself.
5. Undefined type: it is the type of undefined literal. This type of built-in type is the
sub-type of all the types.
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;
}
}
In Javascript Mixins are another way of building up classes from reusable components
is to build them by combining simpler partial classes.
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.
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-
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: –
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.
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-
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
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.
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.
There are two types of scopes are available in Javascript, they are
Global Scope
Local Scope
You can enable Decorators using the command line or editing your tsconfig.json
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.
The classes in TypeScript must follow the structure of the interface. The interface
contains the method declaration, variable declaration.
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.
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 JavaScript source file is in ".js" extension. TypeScript source file is in ".ts" extension.
4 It doesn't support strongly typed or static It supports strongly typed or static typing feature.
typing.
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.
9 In this, number, string are the objects. In this, number, string are the interface.
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 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.
Language
The language comprises elements like new syntax, keywords, type annotations, and
allows us to write TypeScript.
Compiler
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.
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.
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.
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.
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.
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.
o The variable name cannot contain spaces and special character, except the
underscore(_) and the dollar($) sign.
1. Declare type and value in a single statement. Syntax: var [identifier] : [type-
annotation] = value;
$ tsc helloworld.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.
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.
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.
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.
class Student {
studCode: number;
studName: string;
constructor(code: number, name: string) {
this.studName = name;
this.studCode = code;
}
getGrade() : string {
return "A+" ;
}
}
1. Inheritance
2. Encapsulation
3. Polymorphism
4. Abstraction
o Modules
o Classes
o Interfaces
o Inheritance
o Data Types
o Member functions
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
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;
}
}
}
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.
declaration.
5 Example: Example:
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.
Command Line
tsconfig.json
{
"compilerOptions": {
"target": "ES5",
"experimentalDecorators": true
}
}
//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.
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
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:
$ tsd init
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.
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.
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:
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.
{
"compilerOptions": {
"declaration": true,
"emitDecoratorMetadata": false,
"experimentalDecorators": false,
"module": "none",
"moduleResolution": "node"
"removeComments": true,
"sourceMap": true
},
"files": [
"main.ts",
"othermodule.ts"
]
}
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.
1. Encapsulation,
2. Inheritance,
3. Abstraction, and
4. Polymorphism.
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"
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.
The Ambient declarations allow us to safely and easily use existing popular JavaScript
libraries like jquery, angularjs, nodejs, etc.
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.
Example
Example
let empCode: any = 111;
let employeeCode = code as number;
When using TypeScript with JSX, only as-style assertions are allowed.
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
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";
Example
Example
interface Cloner {
clone(animal: Animal): Animal;
}
interface Cloner {
clone(animal: Sheep): Sheep;
}
interface Cloner {
clone(animal: Dog): Dog;
clone(animal: Cat): Cat;
}
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.
o The method must have the same parameter as in the parent class.
Example
Example
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?
Number type: It is used to represent number type values. All the numbers in
TypeScript are stored as floating-point values.
Boolean type: a logical binary switch that holds either true or false
Void type: The type assigned to methods that have no return value.
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;
}
module module_name{
class xyz{
export sum(x, y){
return x+y;
}
}
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
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 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.
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.`);
}
}
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.
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');
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.
class Employee {
private _fullName: string = "";
this._fullName = newName;
}
}
if (employee.fullName) {
console.log(employee.fullName);
}
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]');
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.
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.
class Student {
studCode: number;
studName: string;
constructor(code: number, name: string) {
this.studName = name;
this.studCode = code;
}
18. How does TypeScript relate to JavaScript?
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.
24. Explain Rest parameters and the rules to declare Rest parameters.
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?
Omit<Type, Keys>
For example:
interface Todo {
title: string;
description: string;
completed: boolean;
createdAt: number;
}
For example, you could make an add function that sums the two arguments if
they’re numbers and concatenates them if they’re strings.
You can use the partial mapped type to easily make all properties optional.
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' ...
}
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.
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.
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.
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.
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.
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.
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
Typescript also supports data types provided by all other languages. It includes:
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;
}
}
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.
"compilerOptions": {
"removeComments": true,
"sourceMap": true
},
"files": [
"main.ts",
"othermodule.ts"
] }
The arrow function acts like an additional feature in typescript and is also known as
In this example, => is a lambda operator and (n1 * n2) is the body of function and
n1 + n2; }
{ return n1 * n2; }
{ return n1 / n2; }
number {
//RESULT
console.log(anonyFunc(10, 20)); //Return is 30
//RESULT
console.log(anonyFunc(10, "xyz"));
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
module Vehicle {
class Car {
constructor (
}
var fordCar = Vehicle.Car("Ford", "Figo");
module Vehicle {
constructor (
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
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.
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.
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
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.
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; };
Example:
declare const libraryName;
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;
}
Example:
interface Person {
name: string;
age: number;
}type PartialPerson = Partial<Person>; // Same as next
linesinterface PartialPerson {
name?: string;
age?: number;
}
Example:
let Person = Record<string, number> = {};
Person.age = 25;
Example:
export class Person {}
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;
}
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.
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.
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
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);
}
}
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?
class foo {
private _bar:boolean = false;
get bar():boolean {
return this._bar;
}
set bar(theBar:boolean) {
this._bar = theBar;
}
}
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);
}
}
Can you make the result parameter in save a type-safe function? Rewrite the code to demonstrate.
Answer
class Foo {
// Equivalent
save(callback: NumberCallback): void {
console.log(1)
callback(42);
}
}
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;
}
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.