Professional Documents
Culture Documents
MEAN Unit-4
MEAN Unit-4
TYPESCRIPT
TypeScript:
TypeScript was designed to help developers write more scalable and maintainable
applications by adding features like type checking, interfaces, classes, and modules. It also
provides improved IDE support and better tooling for large codebases.
TypeScript can be used for both frontend and backend development, and is often used with
popular frameworks like React, Angular, and Node.js. It can also be used for writing
serverless functions and mobile applications using frameworks like React Native.
TypeScript is compatible with existing JavaScript code, and developers can gradually adopt
it in their projects. It can also be used in combination with other languages like Rust, C#, and
Python through WebAssembly.
Why TypeScript:
➢ Type Safety: TypeScript is a statically typed language, which means that it provides
type checking during development. This can help catch errors earlier in the
development process, before they cause runtime errors.
➢ Improved Code Quality: TypeScript allows developers to write more maintainable
and scalable code, as it provides features like classes, interfaces, and modules. This
makes it easier to organize code, reuse code, and collaborate with other developers.
➢ Better IDE Support: TypeScript provides better tooling and IDE support than regular
JavaScript. This includes features like code completion, navigation, and refactoring.
This can help developers be more productive and write code faster.
➢ Compatibility with JavaScript: TypeScript is a superset of JavaScript, which means
that it is fully compatible with existing JavaScript code. This makes it easy to gradually
adopt TypeScript in existing projects or libraries.
➢ Strong Community: TypeScript has a large and active community of developers and
contributors, which means that there is a lot of documentation, tools, and libraries
available. This can help developers get started with TypeScript quickly and find
solutions to common problems.
Overall, TypeScript can help developers write better quality code, catch errors earlier, and
be more productive, which can lead to better software development outcomes.
Installing TypeScript:
Install Node.js: TypeScript is built on top of Node.js, so you need to install it first. You can
download and install Node.js from the official website: https://nodejs.org/
Install TypeScript using npm: Once Node.js is installed, you can install TypeScript using npm
(Node Package Manager). Open a terminal or command prompt and run the following
command:
Verify the installation: To verify that TypeScript is installed correctly, open a terminal or
command prompt and run the following command:
tsc -v
This should display the version number of TypeScript that you just installed.
That's it! You have now installed TypeScript on your system and you are ready to start using
it.
Basics of TypeScript:
Functions: You can define functions in TypeScript using the function keyword. You can also
specify the types of the parameters and the return type. For example:
return a + b;
In this example, we have defined a function add that takes two parameters of type number
and returns a value of type number.
Classes: TypeScript supports classes, which allows you to define a blueprint for creating
objects. You can use the class keyword to define a class, and the constructor method to
initialize the object. For example:
class Person {
greet() {
john.greet();
In this example, we have defined a class Person with a name and age property, as well as a
greet method that prints a message to the console. We have also created a new object john
of type Person.
Interfaces: TypeScript supports interfaces, which allow you to define a set of properties and
methods that a class must implement. For example:
interface Animal {
name: string;
age: number;
makeSound(): void;
makeSound() {
console.log("Woof!");
myDog.makeSound();
In this example, we have defined an interface Animal that has a name, age, and makeSound
method. We have also defined a class Dog that implements the Animal interface, and
created a new object myDog of type Dog.
These are just some of the basics of TypeScript. TypeScript also supports advanced features
like generics, decorators, and namespaces, among others.
Functions:
Functions in TypeScript are similar to functions in JavaScript, but with added features to
support static typing and other language features. Here are some key aspects of functions in
TypeScript:
Function Declaration: In TypeScript, you can declare a function using the function keyword,
followed by the function name, parameter list, and return type (if any). For example:
return a + b;
In this example, we have defined a function named add that takes two parameters of type
number and returns a value of type number.
➢ Function Expression: You can also define a function using a function expression,
which assigns the function to a variable. For example:
return a + b;
In this example, we have defined a function expression that assigns a function to the
variable add.
if (name) {
console.log(`Hello, ${name}!`);
} else {
console.log("Hello, world!");
In this example, we have defined a function greet that takes an optional parameter name of
type string. If name is provided, it will print a personalized greeting, otherwise it will print a
generic greeting.
➢ Default Parameters: TypeScript allows you to declare default values for parameters
by using the equal sign. For example:
console.log(`Hello, ${name}!`);
In this example, we have defined a function greet that takes a parameter name of type
string with a default value of "world". If name is not provided, it will use the default value.
➢ Rest Parameters: TypeScript allows you to define rest parameters by prefixing the
last parameter with an ellipsis. Rest parameters allow you to pass an arbitrary
number of arguments to a function. For example:
In this example, we have defined a function multiply that takes a factor parameter of type
number and a rest parameter numbers of type number[]. It multiplies all the numbers in the
numbers array and returns the result multiplied by the factor.
These are just some of the features of functions in TypeScript. TypeScript also supports
function overloading, arrow functions, and other advanced features.
Parameter Types and Return Types:
In TypeScript, you can specify the types of function parameters and the return type of the
function. This allows the TypeScript compiler to check the type safety of your code and
provide helpful error messages if there is a type mismatch. Here's how you can specify
parameter types and return types in TypeScript:
➢ Parameter Types: You can specify the type of a function parameter by using a colon
followed by the type name. For example:
return a + b;
In this example, we have specified that the a and b parameters are of type number.
➢ Return Type: You can specify the return type of a function by adding a colon followed
by the type name after the parameter list. For example:
return a + b;
In this example, we have specified that the function returns a value of type number.
➢ Void Type: If a function does not return a value, you can specify the return type as
void. For example:
console.log(message);
In this example, we have specified that the log function does not return a value by using the
void keyword as the return type.
➢ Optional Parameters: You can specify an optional function parameter by adding a
question mark after the parameter name, and then specifying a default value if the
parameter is not provided. For example:
if (name) {
console.log(`Hello, ${name}!`);
} else {
console.log("Hello, world!");
In this example, we have specified that the name parameter is optional by using the ?
symbol. If the name parameter is not provided, the function will use the default value of
undefined.
➢ Union Types: You can specify that a parameter can have multiple types by using a
union type. For example:
console.log(value);
In this example, we have specified that the value parameter can be of type string or
number.
These are just some of the ways you can specify parameter types and return types in
TypeScript. By using type annotations in your functions, you can make your code more
readable and maintainable, and catch potential errors at compile time.
Arrow Function:
Arrow functions in TypeScript are a shorthand way of writing function expressions. They are
similar to regular functions, but with a more concise syntax. Here's how you can define an
arrow function in TypeScript:
return a + b;
};
In this example, we have defined an arrow function called add that takes two parameters a
and b, both of which are of type number. The function returns the sum of a and b, which is
also of type number.
The parameters are enclosed in parentheses and separated by commas, and the expression
is the code that the function will execute. The expression can be a single line of code, like in
our example, or it can be a block of code enclosed in curly braces.
You can also omit the curly braces and the return keyword if the function has only one
statement:
In this example, we have defined an arrow function called square that takes a parameter x
of type number. The function returns the square of x, which is also of type number.
Arrow functions can be very useful when you need to define small, one-off functions that
don't require a name or a separate function declaration. They can also make your code
more readable by reducing the amount of boilerplate code needed for function definitions.
Function Types: named fun, anonymus fun (in other pdf pg:9)
In TypeScript, functions are first-class citizens and can have types just like any other values.
Function types describe the type of a function, including its parameter types and return
type.
Here's an example of a function type in TypeScript:
In this example, we have defined a function type called AddFunction that takes two
parameters a and b, both of type number, and returns a value of type number.
We can use this function type to define a variable that can hold a function that matches the
type:
return a + b;
};
In this example, we have defined a variable called add of type AddFunction. We have
assigned an arrow function to this variable that matches the function type.
In this example, we have defined a function type called GreetingFunction that takes an
optional parameter name of type string and a rest parameter args of type string[]. The
function has a return type of void.
We can use this function type to define a variable that can hold a function that matches the
type:
if (name) {
console.log(`Hello, ${name}!`);
} else {
console.log("Hello, world!");
}
if (args.length > 0) {
console.log("Additional arguments:");
};
In this example, we have defined a variable called greet of type GreetingFunction. We have
assigned an arrow function to this variable that matches the function type.
Function types are very useful when you want to define functions with specific signatures,
and ensure that only functions that match the type are assigned to a variable or passed as
an argument. They can help catch type errors at compile time and make your code more
robust.
Optional Parameters:
To make a parameter optional, we can use the ? operator after the parameter name in the
function signature. Here's an example:
if (name) {
console.log(`Hello, ${name}!`);
} else {
console.log("Hello, stranger!");
In this example, the name parameter is marked as optional by adding ? after the parameter
name. This means that the parameter may or may not be provided when calling the
function. If the parameter is provided, its value will be used in the greeting message. If it is
not provided, the greeting message will use the default value of "stranger".
Default Parameters:
To define a default value for a parameter, we can simply assign a value to the parameter in
the function signature. Here's an example:
return a + b;
In this example, the b parameter is given a default value of 0 by assigning it in the function
signature. This means that if the b parameter is not provided when calling the function, its
default value of 0 will be used. If the b parameter is provided, its value will be used in the
addition operation.
It's important to note that optional parameters must come after required parameters in the
function signature, and default parameters must come after all required and optional
parameters.
Rest Parameter:
In TypeScript, you can define a function that accepts a variable number of arguments using
a rest parameter. A rest parameter is denoted by the ellipsis ... followed by the parameter
name and it allows a function to accept any number of arguments.
In this example, the multiply function takes a required parameter multiplier of type number
and a rest parameter numbers of type number[]. The rest parameter allows the function to
accept any number of additional arguments, which are collected into an array called
numbers.
The function then uses the reduce method to multiply all the numbers in the numbers array
together, starting with the multiplier value.
In this example, we are calling the multiply function with the multiplier value of 2 and three
additional arguments 3, 4, and 5. The multiply function collects these arguments into the
numbers array and multiplies them together with the reduce method, resulting in the value
of 120.
Rest parameters can be very useful when you need to accept an unknown number of
arguments in a function, such as when working with arrays or lists of data.
Creating an Interface:
To create an interface in TypeScript, we use the interface keyword followed by the name of
the interface and the properties and methods it should contain. Here's an example:
interface Person {
name: string;
age: number;
In this example, we've defined an interface called Person that requires an object to have a
name property of type string, an age property of type number, and a greet method that
takes no arguments and returns no value.
Once an interface is defined, we can use it to define the shape of objects that conform to
that interface. Here's an example of creating an object that conforms to the Person
interface:
name: "Alice",
age: 30,
};
In this example, we've created an object called person that has a name property of type
string, an age property of type number, and a greet method that takes no arguments and
returns no value. This object conforms to the Person interface, so we've declared its type as
Person.
Interfaces can also be extended to create new interfaces that inherit properties and
methods from other interfaces. Here's an example of extending the Person interface to
create a new Employee interface:
interface Employee extends Person {
jobTitle: string;
salary: number;
In this example, we've extended the Person interface to create a new interface called
Employee that requires an object to have all the properties and methods of the Person
interface, as well as a jobTitle property of type string and a salary property of type number.
Duck Typing:
Duck typing is a type system used in some programming languages, including TypeScript. In
duck typing, the type of an object is determined by its behavior, rather than its class or type
hierarchy. If an object quacks like a duck and walks like a duck, it's considered to be a duck,
even if it's not an instance of a Duck class or interface.
interface Animal {
name: string;
console.log(`Hello, ${animal.name}!`);
animal.speak();
}
const cat = {
name: "Fluffy",
};
In this example, we've defined an interface called Animal that requires an object to have a
name property of type string and a speak method that takes no arguments and returns no
value.
We've then defined a greet function that takes an object of type Animal and logs a greeting
message using the object's name property and speak method.
Finally, we've created an object called cat that has a name property of type string and a
speak method that takes no arguments and logs "Meow!" to the console.
Even though cat is not explicitly declared as an instance of the Animal interface, it has all
the properties and methods required by that interface. Therefore, when we call the greet
function with the cat object as an argument, it behaves as if it were an instance of the
Animal interface.
This is an example of duck typing in action, where an object's compatibility with an interface
is determined by its behavior, rather than its type or class hierarchy.
Function Types:
In TypeScript, we can define the types of functions using function types. Function types
describe the types of a function's parameters and return value. They can be used to specify
the types of function parameters when declaring a function or when defining a function
type for a variable or property.
We can use this function type to declare a variable that points to a function that satisfies
this type:
In this example, we've declared a variable called add that has the type AddFunction. We've
also assigned it an arrow function that takes two parameters of type number and returns
their sum.
We can also use function types as parameters in other functions. Here's an example:
function applyOperation(a: number, b: number, op: (x: number, y: number) => number):
number {
console.log(result); // Output: 8
In this example, we've defined a function called applyOperation that takes two parameters
of type number and a third parameter of type (x: number, y: number) => number, which is a
function type that describes a function that takes two parameters of type number and
returns a value of type number.
The applyOperation function calls the function passed as the op parameter with the two a
and b parameters, and returns its result.
We've then called the applyOperation function with 4, 2, and an arrow function that
multiplies its two parameters. The result of the function call is 8, which is logged to the
console.
Function types are a powerful feature of TypeScript that allow us to specify the types of
functions in a concise and expressive way. They can be used to define the types of function
parameters, return values, and even function variables and properties.
Extending Interfaces:
In TypeScript, we can create new interfaces by extending existing ones using the extends
keyword. This allows us to create more specific interfaces that inherit properties and
methods from a more general interface.
interface Animal {
name: string;
age: number;
breed: string;
name: "Buddy",
age: 3,
};
In this example, we've defined an interface called Animal that has three properties: name of
type string, age of type number, and speak of type () => void.
We've then defined a new interface called Dog that extends the Animal interface using the
extends keyword. The Dog interface has all the properties of the Animal interface, plus an
additional property breed of type string.
Finally, we've declared a variable called myDog that has the type Dog. We've assigned it an
object that has all the properties required by the Dog interface, as well as the speak
method.
By extending interfaces, we can create new interfaces that inherit properties and methods
from existing ones, making it easier to define complex types with reusable code. We can
also use interface extension to define more specific types that share common properties
and methods, which helps us to write more modular and maintainable code.
Classes:
In TypeScript, classes are a way to define objects with properties and methods. Classes
provide a blueprint for creating objects, and allow us to define the properties and methods
that those objects will have.
class Person {
name: string;
age: number;
this.name = name;
this.age = age;
sayHello() {
console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
In this example, we've defined a class called Person with two properties: name of type
string and age of type number. We've also defined a constructor method that takes two
parameters, name and age, and assigns their values to the corresponding properties.
We've then defined a sayHello method that logs a message to the console using the name
and age properties.
We've created an instance of the Person class using the new keyword, passing in the name
and age parameters to the constructor. We've then called the sayHello method on the
person object, which logs a message to the console.
Classes in TypeScript can also inherit from other classes using the extends keyword. This
allows us to define more specific classes that inherit properties and methods from a more
general class.
studentId: number;
super(name, age);
this.studentId = studentId;
study() {
console.log(`${this.name} is studying with student ID ${this.studentId}.`);
In this example, we've defined a class called Student that extends the Person class using the
extends keyword. The Student class has an additional property studentId of type number,
and a study method that logs a message to the console using the name and studentId
properties.
We've created an instance of the Student class using the new keyword, passing in the name,
age, and studentId parameters to the constructor. We've then called the sayHello and study
methods on the student object, which logs messages to the console.
Constructor:
In TypeScript, the constructor is a special method that is used to create and initialize objects
created from a class. It is executed automatically when an object is instantiated from a
class.
The constructor method has the same name as the class and can accept zero or more
parameters. It is defined using the constructor keyword followed by parentheses that
contain the parameter list and the method body.
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
In this example, we've defined a class called Person with two properties: name of type
string and age of type number. We've also defined a constructor method that takes two
parameters, name and age, and assigns their values to the corresponding properties using
the this keyword.
We can create an instance of the Person class by using the new keyword and passing in the
name and age parameters to the constructor:
In this example, we've created a new object called person from the Person class, passing in
the values "John" and 30 for the name and age parameters, respectively.
class Person {
name: string;
age: number;
this.name = name;
this.age = age;
}
In this example, we've set default values for the name and age parameters in the
constructor. If no values are passed in when creating an instance of the Person class, the
default values of "Unknown" and 0 will be used for name and age, respectively.
The constructor method can also include access modifiers such as public, private, and
protected to control the visibility of the class properties.
Access Modifiers:
In TypeScript, access modifiers are used to control the visibility and accessibility of class
members (properties and methods) from outside the class. There are three access modifiers
in TypeScript: public, private, and protected.
➢ public modifier: Members declared as public are accessible from anywhere, both
inside and outside the class. This is the default access modifier if none is specified.
Example:
class Person {
constructor(name: string) {
this.name = name;
In this example, name property of the Person class is declared as public. We can access it
outside the class using the person.name statement.
➢ private modifier: Members declared as private are only accessible within the class.
They are not accessible from outside the class, not even from derived classes.
Example:
class Person {
constructor(name: string) {
this.name = name;
greet() {
In this example, name property of the Person class is declared as private. We can't access it
outside the class using the person.name statement. But we can access it within the class
using the this.name statement.
➢ protected modifier: Members declared as protected are accessible within the class
and its subclasses. They are not accessible from outside the class hierarchy.
Example:
class Person {
constructor(name: string) {
this.name = name;
super(name);
this.department = department;
public getDetails() {
In this example, name property of the Person class is declared as protected. We can't access
it outside the class hierarchy using the emp.name statement. But we can access it within
the Employee class (subclass of Person class) using the this.name statement.
class Person {
name: string;
age: number;
this.name = name;
this.age = age;
greet(): void {
In this example, the Person class has two properties: name and age. The constructor
function is used to set the values of these properties when a new instance of the class is
created.
The greet method is a function that belongs to the Person class. It can be called on an
instance of the class using the person.greet() statement. This method uses the this keyword
to refer to the instance of the class and access its properties.
Note that by default, properties in TypeScript are public, which means they can be accessed
from outside the class.
You can also specify the access modifier for a property using the public, private, or
protected keyword. For example:
class Person {
this.name = name;
this.age = age;
getName(): string {
return this.name;
getAge(): number {
return this.age;
console.log(person.getAge()); // Output: 30
In this example, the name property is declared as private, which means it can only be
accessed within the Person class. The age property is declared as protected, which means it
can be accessed within the Person class and its subclasses.
The getName and getAge methods are used to get the values of the name and age
properties, respectively. These methods can be called on an instance of the Person class,
but the name and age properties cannot be accessed directly from outside the class.
In TypeScript, a namespace is a way to group related code together and prevent naming
collisions. Namespaces are similar to modules, but while modules are used to organize code
that will be compiled to separate files, namespaces are used to organize code within a
single file.
To create a namespace in TypeScript, you can use the namespace keyword followed by the
namespace name and the code that should be included in the namespace. Here's an
example:
namespace MyNamespace {
name: string;
age: number;
}
let person: MyNamespace.Person = { name: 'John', age: 30 };
In this example, we've created a namespace called MyNamespace. Inside the namespace,
we've defined an interface called Person and a function called greet that takes a Person
object as a parameter and logs a greeting to the console.
Note that we've used the export keyword to make the Person interface and the greet
function available outside the namespace.
To use the Person interface and the greet function, we can refer to them using the
namespace name followed by a dot notation, like MyNamespace.Person and
MyNamespace.greet.
Using namespaces can help avoid naming collisions, especially when working with large
projects that have many modules and components. However, it's important to use them
judiciously and avoid creating deeply nested namespaces, as this can make the code harder
to read and maintain.
In TypeScript, modules are used to organize code into reusable, self-contained units of
functionality. Each module can have its own private variables and functions, which are not
accessible from outside the module, as well as public variables and functions that can be
used by other modules.
To create a module in TypeScript, you can use the export keyword to export variables and
functions that you want to make available outside the module. Here's an example:
name: string;
age: number;
In this example, we've created a module that exports an interface called Person and a
function called greet.
To use the Person interface and the greet function in another module or in your application
code, you can use the import statement. Here's an example:
In this example, we've imported the Person interface and the greet function from the my-
module.ts file using the import statement. We can then use these exported variables and
functions as if they were defined in our own code.
Note that we've used the file path './my-module' as the import specifier to indicate the
location of the module. This path is relative to the file that is importing the module.
You can also export classes and other constructs from a module in TypeScript. To export a
class, you can use the export keyword before the class definition. To import a class from a
module, you can use the import statement with the same syntax as for variables and
functions.
console.log(`${this.message}, ${name}!`);
}
import { Greeter } from './greeter';
In this example, we've defined a Greeter class in a module and exported it using the export
keyword. We can then import the Greeter class in another module and use it to create
instances of the Greeter class.
When working with modules in TypeScript, you have several options for the module format
and the module loader that you can use to load and execute your modules.
Module formats specify the syntax used to define and import modules in your code, while
module loaders specify how modules are loaded and executed at runtime. Here are some of
the most common module formats and loaders used in TypeScript:
Module Formats
CommonJS
The CommonJS module format is used in Node.js and allows you to define modules using
the module.exports and require statements. This format is well-suited for server-side
development, but may not be the best choice for web applications due to its synchronous
loading behavior.
ES modules
ES modules are the standard module format for JavaScript, and are supported by modern
browsers and Node.js. ES modules use the import and export statements to define and
import modules. This format allows for more fine-grained control over dependencies and
supports asynchronous loading, making it a good choice for web applications.
AMD
Asynchronous Module Definition (AMD) is a module format used by RequireJS and other
AMD loaders. AMD modules use the define function to define modules, and the require
function to import them. This format is well-suited for web applications, as it supports
asynchronous loading and allows for modular code organization.
Module Loaders
Node.js
Node.js is a popular server-side platform that uses the CommonJS module format and the
Node.js module loader to load modules at runtime. Node.js provides a built-in require
function that allows you to load modules from the local file system or from third-party
packages installed via npm.
Webpack
Webpack is a popular module bundler that can be used to package your TypeScript modules
into a single JavaScript file that can be loaded in the browser. Webpack supports multiple
module formats and can handle dependencies between modules, making it a powerful tool
for building complex web applications.
SystemJS
SystemJS is a dynamic module loader that can load modules in multiple formats, including
CommonJS, AMD, and ES modules. SystemJS allows you to load modules at runtime, which
can be useful for applications that need to dynamically load modules based on user
interactions or other runtime conditions.
In summary, when working with TypeScript modules, you have several options for the
module format and loader that you can use. The choice of format and loader will depend on
the requirements of your application and the platforms on which it will be deployed.
Module Vs Namespace:
In TypeScript, both modules and namespaces serve as a way to organize code and
encapsulate functionality, but they are not interchangeable and have different use cases.
Modules
Modules in TypeScript are used to define and organize code in separate files, and to
manage dependencies between different parts of an application. A module can export
variables, functions, classes, and other entities that can be consumed by other modules.
Modules in TypeScript support various module formats, such as CommonJS, AMD, and ES6
modules, and can be loaded using module loaders such as Node.js, Webpack, and SystemJS.
Namespaces
Namespaces in TypeScript are used to group related code and avoid naming conflicts. A
namespace can contain variables, functions, classes, and interfaces, and can be nested to
create a hierarchical organization of code.
Unlike modules, namespaces do not have a separate file scope, and all entities in a
namespace are in the same global scope. This can sometimes lead to naming conflicts if
multiple namespaces define entities with the same name.
In general, you should use modules in TypeScript to organize code across different files and
manage dependencies between different parts of an application. Modules allow you to
easily reuse and share code, and provide a clear separation of concerns between different
parts of an application.
Namespaces, on the other hand, are best used to organize related code within a single file
or a small set of files. Namespaces can be useful for avoiding naming conflicts, but should
be used sparingly to avoid cluttering the global namespace.
In summary, while both modules and namespaces are useful for organizing code in
TypeScript, they have different use cases and should be used appropriately depending on
the requirements of your application.
In TypeScript, generics are represented by type parameters, which are placeholders for
specific types. Type parameters are declared using angle brackets < >, and can be used to
define the type of function parameters, return types, and class properties.
Here's an example of a simple generic function in TypeScript that takes an array of any type
and returns the first element of the array:
return arr[0];
console.log(getFirst<number>(arr1)); // output: 1
In this example, the getFirst function takes an array of type T and returns the first element
of that array, which is also of type T. The <T> syntax in the function signature declares the
type parameter T, which can be any type.
When calling the function, we specify the type of T using angle brackets. In the first call, we
specify T as number, and in the second call, we specify T as string.
Generics can also be used to define classes and interfaces. Here's an example of a generic
class that represents a stack of elements of any type:
class Stack<T> {
this.items.push(item);
pop(): T | undefined {
return this.items.pop();
stack1.push(1);
stack1.push(2);
console.log(stack1.pop()); // output: 2
stack2.push("a");
stack2.push("b");
In this example, the Stack class is defined as a generic class with a type parameter T. The
class contains two methods, push and pop, which operate on elements of type T. When
creating an instance of the Stack class, we specify the type of T using angle brackets, just
like we did with the getFirst function.
Generics provide a powerful way to write reusable code in TypeScript, and are used
extensively in many popular libraries and frameworks, such as Angular and React.
Type parameters are declared using angle brackets < > and can be used to define the type
of function parameters, return types, and class properties. For example, consider the
following generic function that swaps two elements of an array:
arr[i] = arr[j];
arr[j] = temp;
In this function, T is a type parameter that represents the type of elements in the array.
When calling the function, you specify the actual type of T, such as number or string.
swap<number>(arr1, 0, 2); // swaps the first and third elements of the array
Type parameters can also be used to define generic classes. For example, consider the
following Stack class that can hold elements of any type:
class Stack<T> {
push(item: T) {
this.items.push(item);
pop(): T | undefined {
return this.items.pop();
In this class, T is a type parameter that represents the type of elements in the stack. When
creating an instance of the Stack class, you specify the actual type of T, such as number or
string.
stack1.push(1);
stack1.push(2);
console.log(stack1.pop()); // prints 2
stack2.push("hello");
stack2.push("world");
Type parameters provide a powerful way to write generic code in TypeScript, making it
more flexible and reusable.
Generic Functions:
In TypeScript, you can create generic functions using type parameters. Generic functions
allow you to write code that works with different types of data without having to specify
the type upfront.
Here's an example of a generic function that takes an array of values of any type and
returns the last element of the array:
function getLast<T>(arr: T[]): T | undefined {
In this function, T is a type parameter that represents the type of elements in the array.
When the function is called, the type parameter is replaced with an actual type, such as
number or string.
Here's an example of how you can call the getLast function with different types of arrays:
Note that the inferred type of the return value depends on the type of the array passed as
an argument. In this example, the return type is either the type of the elements in the array
or undefined if the array is empty.
You can also explicitly specify the type parameter when calling the function:
Generic functions provide a powerful way to write reusable code in TypeScript that can
work with different types of data.
Generic Constraints:
In TypeScript, you can use generic constraints to restrict the types that can be used as type
parameters in generic functions or classes. A generic constraint allows you to specify that a
type parameter must extend a particular type or set of types.
Here's an example of a generic function that uses a generic constraint to restrict the types
of its input:
interface HasLength {
length: number;
return arr[0];
In this function, the generic type parameter T is constrained to be a type that implements
the HasLength interface. The HasLength interface requires that any implementing type must
have a length property of type number.
The return type of the getFirst function uses a conditional type to determine whether the
input array is an array of some type or not. If it is, the function returns the type of the
elements of the array, otherwise it returns the original type T.
Here's an example of how you can call the getFirst function with different types of input:
Note that the inferred type of the return value depends on the type of the input passed as
an argument. In this example, the return type is either the type of the elements in the array
or the original type T.
Generic constraints provide a powerful way to write more type-safe and reusable code in
TypeScript by ensuring that the types used as type parameters meet certain requirements.
MONGO DB
Mongo DB:
MongoDB is designed to be highly scalable, fault-tolerant, and easy to use. It provides high-
performance, real-time data access, and can handle large volumes of data with ease.
MongoDB also offers a range of advanced features, such as support for distributed
databases, automatic sharding, and full-text search, that make it a popular choice for
modern web and mobile applications.
There are several reasons why MongoDB is a popular choice for modern web and mobile
applications:
1. Flexible data model: MongoDB's document-oriented data model allows you to store data
in a flexible, semi-structured format, making it easy to store and retrieve complex,
unstructured data, such as social media posts, user comments, and product catalogs.
2. Scalability and performance: MongoDB is designed to be highly scalable and can handle
large volumes of data with ease. It also provides high-performance, real-time data access,
making it ideal for applications that require fast data retrieval.
3. Easy to use: MongoDB has a user-friendly interface, and its query language is similar to
JavaScript, making it easy for developers to learn and use.
4. No need for a separate ORM: Because MongoDB uses a document-oriented data model,
there is no need for a separate Object-Relational Mapping (ORM) layer, which can simplify
development and reduce complexity.
6. Open source: MongoDB is open source software, which means it is free to use and can be
modified and distributed by anyone.
The Introduction module for MongoDB covers the basics of MongoDB, including its
features, data model, installation, and setup. Here's a brief overview of what you can expect
to learn in this module:
1. Introduction to MongoDB: You will learn what MongoDB is, its features, and how it
differs from traditional relational databases.
2. MongoDB Data Model: You will learn about MongoDB's document-oriented data model,
including how data is organized and stored in collections and documents.
3. Installation and Setup: You will learn how to install and set up MongoDB on your local
machine, including configuring the database server and connecting to the MongoDB shell.
4. CRUD Operations: You will learn how to perform basic CRUD (Create, Read, Update,
Delete) operations in MongoDB, including inserting documents, querying data, and
updating and deleting documents.
5. Indexing: You will learn how to create indexes in MongoDB to improve query
performance and optimize data retrieval.
By the end of the Introduction module, you will have a solid understanding of MongoDB's
data model, how to install and set up MongoDB on your local machine, and how to perform
basic CRUD operations and indexing in MongoDB.
This knowledge will serve as a foundation for further learning in MongoDB and building
applications with this popular NoSQL database.
2. Collections: Documents are organized into collections, which are similar to tables in a
traditional database. Collections can contain any number of documents, and each
document can have a different structure.
3. Dynamic Schema: MongoDB has a dynamic schema, which means that you don't need to
define a fixed schema before inserting data. You can insert documents with different
structures and fields at any time.
4. Indexing: MongoDB supports various types of indexes, which can improve query
performance and optimize data retrieval. Indexes can be created on any field within a
document, including fields within nested objects and arrays.
5. Querying: MongoDB provides a powerful query language that allows you to retrieve data
from collections based on specific criteria. You can use a wide range of operators and
functions to filter, sort, and aggregate data.
Overall, MongoDB's document database provides a flexible and scalable way to store and
retrieve data, making it an ideal choice for modern web and mobile applications. By using a
document-oriented data model, MongoDB allows you to store and access complex,
unstructured data with ease, and provides powerful query and aggregation capabilities to
help you analyze and manipulate your data.
Understanding JSON:
MongoDB stores data in the form of JSON-like documents, which means that data is
represented in a semi-structured format that is similar to JSON. Here's how JSON is used in
MongoDB:
Data Format: MongoDB stores data in documents, which are similar to JSON objects. Each
document is represented as a set of key-value pairs, with field names and values separated
by a colon. For example, a document in MongoDB could look like this:
"_id": ObjectId("60b4a6f786ec6b00516d7f1a"),
"age": 35,
"email": "john.smith@example.com",
"address": {
"city": "Anytown",
"state": "CA",
"zip": "12345"
Dynamic Schema: MongoDB has a dynamic schema, which means that you can insert
documents with different structures and fields at any time. This flexibility allows you to
store and access data without having to define a fixed schema beforehand.
Querying: MongoDB provides a powerful query language that allows you to retrieve data
from documents based on specific criteria.
The query language uses a syntax that is similar to JSON, with key-value pairs and operators.
For example, to retrieve all documents with an age greater than 30, you could use the
following query:
Indexing: MongoDB supports various types of indexes that can improve query performance
and optimize data retrieval. Indexes can be created on any field within a document,
including fields within nested objects and arrays.
Overall, MongoDB's use of JSON-like documents makes it easy to store and access data in a
flexible and scalable way. By using a document-oriented data model, MongoDB allows you
to store and access complex, unstructured data with ease, and provides powerful query and
indexing capabilities to help you retrieve and analyze your data.
MongoDB Structure
4. Field: A field is a key-value pair within a document. Fields are similar to columns in a table
in a traditional relational database. Fields can contain a variety of data types, including
strings, numbers, booleans, dates, and more.
5. Index: A MongoDB index is a data structure that improves the speed of queries on a
collection. Indexes can be created on any field within a document, including fields within
nested objects and arrays. MongoDB supports various types of indexes, including single
field, compound, and text indexes.
6. GridFS: MongoDB provides a protocol for storing and retrieving large files, called GridFS.
GridFS is useful when you need to store files that exceed the BSON document size limit of
16MB.
Mongo DB Architecture
2. Replica Set: A replica set is a group of MongoDB servers that work together to provide
high availability and data redundancy. Each replica set contains a primary node and one or
more secondary nodes. The primary node handles all write operations, while the secondary
nodes replicate the data from the primary node and can take over if the primary node fails.
4. Memory Mapped Files (MMAP): MongoDB uses Memory Mapped Files (MMAP) for data
storage. This allows MongoDB to use the operating system's virtual memory system for
caching frequently accessed data, which can improve performance.
6. Query Router: The query router is responsible for directing queries to the appropriate
shard in a sharded cluster. The query router acts as a proxy between clients and the shard
servers.
7. Balancer: The balancer is responsible for balancing the distribution of data across shards
in a sharded cluster. The balancer runs as a background process and periodically checks the
distribution of data across shards, moving chunks of data as necessary to maintain a
balanced distribution.
8. Backup and Recovery: MongoDB provides built-in tools for backup and recovery,
including hot backups, point-in-time recovery, and backup validation.
MongoDB provides several options for remote management of its database instances. Here
are some of the most common options:
1. MongoDB Atlas: MongoDB Atlas is a fully managed cloud database service that provides
a GUI-based interface for managing MongoDB clusters in the cloud. It offers automatic
scaling, backup and recovery, and built-in security features such as encryption and
monitoring.
Overall, MongoDB provides several options for remote management of its database
instances, ranging from fully managed cloud services to comprehensive on-premise
solutions. These tools offer automation, monitoring, backup and recovery, and security
features that can help you manage your MongoDB databases more effectively.
mkdir C:\data\db
➢ Add the MongoDB binaries to your system's PATH environment variable by following
these steps:
• Open the Control Panel and go to System and Security > System > Advanced system
settings > Environment Variables.
• Under "System variables", find the "Path" variable and click "Edit".
• Add the path to the MongoDB binaries to the end of the "Variable value" field,
separated by a semicolon. For example: C:\Program Files\MongoDB\Server\4.4\bin
➢ Start the MongoDB server by opening a command prompt and running the following
command:
Mongod
➢ Verify that MongoDB is running by opening another command prompt and running
the following command:
Mongo
That's it! You should now have MongoDB up and running on your local computer.
mkdir -p /data/db
➢ Set the appropriate permissions for the data directory by running the following
command:
Mongod
➢ Verify that MongoDB is running by opening another terminal window and running the
following command:
Mongo
1. MongoDB Atlas: MongoDB Atlas is a fully managed cloud database service that provides
a GUI-based interface for managing MongoDB clusters in the cloud. It offers automatic
scaling, backup and recovery, and built-in security features such as encryption and
monitoring.
3. Charts: Charts is a data visualization service that enables developers to create interactive
charts and graphs from their MongoDB data. It includes a wide range of chart types and
customization options, and can be embedded in web applications or shared via URLs.
Overall, MongoDB Cloud provides developers with a range of cloud-based services that
make it easier to deploy, manage, and scale their MongoDB database instances. These
services provide features such as automatic scaling, backup and recovery, security, data
synchronization, and data visualization, and can help developers build more scalable,
secure, and performant applications.
2. Create a new project: Once you're logged in, create a new project by clicking the "New
Project" button. Give your project a name and click "Create Project".
3. Create a new cluster: Within your project, click the "Build a Cluster" button. This will
bring you to the cluster creation page.
4. Choose a cloud provider and region: Choose your cloud provider and region where you
want your cluster to be deployed. You can choose from AWS, Google Cloud, or Azure.
5. Choose a cluster tier: Select the cluster tier that meets your needs. MongoDB Atlas offers
a range of cluster tiers, from a free tier suitable for development and testing to large-scale
clusters for production workloads.
6. Configure your cluster settings: Configure your cluster settings such as the number of
nodes, disk size, backup options, and more. You can also choose to enable features such as
encryption and network peering.
7. Deploy your cluster: After you've configured your settings, click "Create Cluster" to
deploy your new MongoDB Atlas cluster.
8. Wait for your cluster to deploy: MongoDB Atlas will create your new cluster in the
background. This process can take a few minutes to complete. You can track the progress of
your deployment on the "Clusters" page in your MongoDB Atlas dashboard.
Once your cluster is deployed, you can connect to it using the connection string provided by
MongoDB Atlas. You can also manage your cluster, configure security settings, set up
monitoring and alerts, and more, all from your MongoDB Atlas dashboard.
There are several GUI tools available for MongoDB that provide a graphical user interface
for managing and interacting with MongoDB databases. Here are a few popular options:
1. MongoDB Compass: MongoDB Compass is the official GUI for MongoDB. It provides a
visual interface for managing databases, collections, and documents, as well as features
such as query analysis, aggregation pipeline visualization, and index optimization. MongoDB
Compass is available for free and can be downloaded from the MongoDB website.
2. Studio 3T: Studio 3T is a popular commercial GUI tool for MongoDB that provides
features such as SQL querying, visual schema design, and data import/export. It also
includes a variety of productivity tools such as code generation, aggregation pipeline
building, and regular expression testing.
3. Robo 3T: Robo 3T is a free and open-source GUI for MongoDB that provides a simple and
lightweight interface for managing databases and collections. It includes features such as
querying, indexing, and data export/import.
5. Aqua Data Studio: Aqua Data Studio is a commercial multi-database GUI tool that
supports MongoDB as well as other database systems. It includes features such as visual
query builder, schema synchronization, and data import/export.
These GUI tools provide a convenient and user-friendly way to manage MongoDB databases
and perform various tasks such as querying, indexing, and data manipulation.
Sure, here are the steps to install and configure MongoDB Compass:
2. Install MongoDB Compass: Run the installer and follow the prompts to install MongoDB
Compass on your computer.
3. Launch MongoDB Compass: Once you've installed MongoDB Compass, launch the
application from your applications menu or desktop shortcut.
5. Configure connection settings: In the connection settings dialog, enter the connection
details for your MongoDB instance, including the hostname, port number, and
authentication details if necessary. You can also configure additional options such as SSL
encryption and SSH tunneling if needed.
6. Test the connection: Once you've configured your connection settings, click the
"Connect" button to test the connection. If the connection is successful, you'll be able to
see a list of databases and collections in the left-hand navigation pane.
7. Explore data with MongoDB Compass: With MongoDB Compass connected to your
MongoDB instance, you can explore your data using the intuitive GUI interface. You can
view documents, create new documents, run queries, and perform other actions on your
MongoDB data.
That's it! With MongoDB Compass installed and connected to your MongoDB instance, you
can manage your databases and collections with ease.
The MongoDB shell is a command-line interface for interacting with MongoDB databases.
It's a powerful tool that allows you to manage your databases, collections, and documents
using a simple yet flexible syntax.
To launch the MongoDB shell, you can simply open a terminal or command prompt and
type `mongo`. This will start the shell and connect you to the default MongoDB instance
running on your local machine.
Once you're connected to the shell, you can perform a variety of tasks such as:
1. Creating and managing databases and collections
The MongoDB shell uses a JavaScript-based syntax, which means that you can write scripts
and functions to automate common tasks and perform more complex operations.
Here are a few basic commands to get you started with the MongoDB shell:
1. `show dbs`: Show a list of all databases on the current MongoDB instance.
These are just a few examples of the many commands available in the MongoDB shell. With
some practice and experimentation, you can become proficient at using the shell to manage
your MongoDB databases and collections.
This means that you can use all of the features of the JavaScript language when working
with the MongoDB shell. For example, you can define variables, use loops and conditional
statements, and even define functions to perform more complex operations.
Here's an example of using a loop and a conditional statement in the MongoDB shell to
update multiple documents in a collection:
// Loop through each document and update the "status" field to "inactive"
documents.forEach(function(doc) {
collection.updateOne(
{ "_id": doc._id },
);
});
In this example, we're using the `find()` method to retrieve all documents in the
"mycollection" collection where the "status" field is set to "active". We then loop through
each document using the `forEach()` method, and update the "status" field to "inactive"
using the `updateOne()` method.
This is just a simple example, but the MongoDB shell and its JavaScript engine allow you to
perform much more complex operations and queries. With some practice and
experimentation, you can become proficient at using the shell to manage your MongoDB
databases and collections.
The MongoDB shell uses a JavaScript-based syntax for executing commands and interacting
with the database. This means that you can use all of the features of the JavaScript
language when working with MongoDB, including variables, loops, conditional statements,
and functions.
Here are some basic examples of the JavaScript syntax used in the MongoDB shell:
1. Variables: You can define variables using the `var` keyword. For example:
var x = 5;
2. Loops: You can use loops like `for` and `while` to iterate over data. For example:
print(i);
3. Conditional statements: You can use `if` and `else` statements to perform conditional
logic. For example:
var x = 5;
if (x > 10) {
} else {
}
4. Functions: You can define and use functions to perform more complex operations. For
example:
function add(x, y) {
return x + y;
print(result); // prints 7
These are just a few examples of the JavaScript syntax used in the MongoDB shell. With
some practice and experimentation, you can become proficient at using the shell to manage
your MongoDB databases and collections.
MongoDB supports a wide range of data types that you can use to store and manipulate
data in your databases. Here's an overview of the most commonly used MongoDB data
types:
1. String: A sequence of UTF-8 characters, used to represent text. Strings are enclosed in
double quotes (").
4. Date: A date and time value, represented as a 64-bit integer that stores the number of
milliseconds since the Unix epoch (January 1, 1970).
5. Object: A nested document that can contain other fields and values.
6. Array: An ordered list of values, represented as a nested document with integer keys.
7. ObjectId: A unique identifier for a document, automatically generated by MongoDB.
ObjectId values are 12-byte binary values that include a timestamp, a machine identifier, a
process identifier, and a counter.
8. Binary data: A binary value, used to represent arbitrary data such as images or audio
files.
9. Regular expression: A pattern used to match text, represented as a string with optional
flags.
These data types can be used in a variety of ways in MongoDB, and you can also create your
own custom data types using MongoDB's flexible schema design capabilities.
CRUD stands for Create, Read, Update, and Delete, and these are the basic operations that
you can perform on documents in MongoDB. Here's a brief overview of each operation:
1. Create: To create a new document in MongoDB, you can use the `insertOne` or
`insertMany` method. For example:
This will insert a new document with the `name` and `age` fields into the `myCollection`
collection.
2. Read: To retrieve documents from MongoDB, you can use the `find` method. For
example:
This will return all documents in the `myCollection` collection that have a `name` field equal
to "John".
3. Update: To update an existing document in MongoDB, you can use the `updateOne` or
`updateMany` method. For example:
db.myCollection.updateOne({ name: "John" }, { $set: { age: 35 } });
This will update the `age` field of the first document in the `myCollection` collection that has
a `name` field equal to "John" to 35.
4. Delete: To remove documents from MongoDB, you can use the `deleteOne` or
`deleteMany` method. For example:
This will delete the first document in the `myCollection` collection that has a `name` field
equal to "John".
These are the basic CRUD operations that you can perform on documents in MongoDB.
With these operations, you can manage your data and collections in a flexible and powerful
way.
In MongoDB, you can create and delete databases and collections using the following
commands:
1. Creating a database: To create a new database in MongoDB, you can use the `use`
command followed by the name of the database. For example:
use myDatabase
This will create a new database called `myDatabase`. Note that this command does not
actually create the database until you insert data into it.
2. Creating a collection: To create a new collection in MongoDB, you can use the
`createCollection` method. For example:
db.createCollection("myCollection")
This will create a new collection called `myCollection` in the current database.
3. Deleting a database: To delete a database in MongoDB, you can use the `dropDatabase`
method. For example:
use myDatabase
db.dropDatabase()
This will delete the `myDatabase` database and all its collections.
4. Deleting a collection: To delete a collection in MongoDB, you can use the `drop` method.
For example:
db.myCollection.drop()
This will delete the `myCollection` collection from the current database.
In MongoDB, queries are used to retrieve data from a collection based on certain criteria.
MongoDB uses a powerful and flexible query language that allows you to filter, sort, and
limit the data returned by a query.
db.myCollection.find()
This will return all documents in the `myCollection` collection that have a `name` field equal
to "John".
This will return all documents in the `myCollection` collection that have a `name` field equal
to "John" and an `age` field greater than 30.
db.myCollection.find().sort({ age: -1 })
This will return all documents in the `myCollection` collection sorted by the `age` field in
descending order.
db.myCollection.find().limit(10)
These are just a few examples of the types of queries you can perform in MongoDB. With its
flexible and powerful query language, you can retrieve data from your collections in a wide
variety of ways.
THANK YOU
HAPPY LEARNING