Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
31 views

Unit I - Notes

Uploaded by

Dr. R. Gowri CIT
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

Unit I - Notes

Uploaded by

Dr. R. Gowri CIT
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

Course Code L T P C

WEB FRAMEWORKS
CS2404 3 0 2 4

Course Objectives:

1. To build scalable web applications using Angular


2. To import and export functionalities of modules using Angular
3. To create reusable UI components using React
4. To manage state of the application more efficiently using React Hook
5. To containerize the applications using Docker ad Kubernetes

UNIT I – ANGULAR V 12 9

Introduction to Angular – Typescript (Arrays, Functions, classes) – JS vs TS – Angular CLI Installation –


Components – Data Binding – Routing on Angular - Directives

UNIT II – ANGULAR MODULES AND MATERIAL 9

Angular Modules – HTTP client, Forms Module – Angular Service Files – Dependancy Injection –
Angular Material – Connecting Angular with Back End
UNIT III – REACT V 18 9

Introduction to React – Setting development environment – create app – JSX syntax – properties and
states – components – React routing – API request
UNIT IV – REACT HOOKS 9

React Hooks – useState – useEffect – useCallback – useMemo – useContext – useReducer –


Introduction to React Native
UNIT V – CONTAINERIZATION 9

Introduction to Image and Container – Docker – Containers – Docker Images, Docker file, Docker
Network – Docker Compose - Kubernetes
45 PERIODS

PRACTICAL EXERCISES: 30 PERIODS

1. Project – Create an angular app with n components and add routing


2. Project – Add functionalities, validation and database with above components
3. Project – Create Login System using React
4. Project – Create Flight Management system

COURSE OUTCOMES:

Upon completion of the course, students will be able to:

1. CO1: Build scalable web applications using Angular


2. CO2: Import and export functionalities of modules using Angular
3. CO3: Create reusable UI components using React
4. CO4: Manage state of the application more efficiently using React Hook
5. CO5: Containerize the applications using Docker ad Kubernetes

TEXT BOOKS:

1. Nate Murray, Felipe Coury, Ari Lerner, Carlos Taborda, “ The Ng book — The Complete Book
on Angular”
2. The Road to React, Robin Wieruch,2023.
3. The Docker Book: Containerization is the new virtualization, James Turnbull, 2014.
4. The Kubernetes Book, Nigel Poulton, 2023.

ONLINE RESOURCES:

1. https://angular.io/docs
2. https://react.dev/
3. https://react.dev/reference/react
4. https://docs.docker.com/
5. https://kubernetes.io/docs/home/
Introduction to Angular & Angular CLI
Installation

Angular is an application-design framework and development platform for creating efficient


and sophisticated single-page apps. It is built on TypeScript.

As a platform, Angular includes:

 A component-based framework for building scalable web applications


 A collection of well-integrated libraries that cover a wide variety of features,
including routing, forms management, client-server communication, and more
 A suite of developer tools to help us develop, build, test, and update our code

Local development environment


Step 1 - Identify the version of node.js that Angular requires
Angular requires an active LTS or maintenance LTS version of Node.

From a Terminal window:

1. Run the following command: node --version


2. Confirm that the version number displayed meets the requirements.
Step 2 - Install the correct version of node.js for Angular
Step 3 - Install the latest version of Angular

With node.js and npm installed, the next step is to install the Angular CLI which provides
tooling for effective Angular development.

From a Terminal window run the following command: npm install -g @angular/cli.

Step 4 - Install integrated development environment (IDE)


1. Visual Studio Code
Create a new workspace and an initial application

Develop applications in the context of an Angular workspace. A workspace contains the files
for one or more projects. A project is the set of files that make up an application or a library.

To create a new workspace and an initial project:

1. Ensure that you aren't already in an Angular workspace directory. For example, if
you're in the Getting Started workspace from an earlier exercise, navigate to its
parent.
2. Run ng new followed by the application name as shown here:

ng new angular-tour-of-heroes
3. ng new prompts you for information about features to include in the initial project.
Accept the defaults by pressing the Enter or Return key.

ng new installs the necessary npm packages and other dependencies that Angular requires.
This can take a few minutes.

ng new also creates the following workspace and starter project files:

 A new workspace, with a root directory named angular-tour-of-heroes


 An initial skeleton application project in the src/app subdirectory
 Related configuration files

The initial application project contains a simple application that's ready to run.

Serve the application

Go to the workspace directory and launch the application.

cd angular-tour-of-heroes

ng serve --open

The ng serve command:

 Builds the application


 Starts the development server
 Watches the source files
 Rebuilds the application as you make changes

The --open flag opens a browser to http://localhost:4200.

You should see the application running in your browser.

https://angular.io/tutorial/first-app/first-app-lesson-01
Components
Components are the main building blocks for Angular applications. Each component consists
of:

 An HTML template that declares what renders on the page


 A TypeScript class that defines behavior
 A CSS selector that defines how the component is used in a template
 Optionally, CSS styles applied to the template

To create a component, verify that you have met the following prerequisites:

1. Install the Angular CLI.


2. Create an Angular workspace with initial application. If you don't have a project,
create one using ng new <project-name>, where <project-name> is the name of your
Angular application.
Creating a component

The best way to create a component is with the Angular CLI.

Creating a component using the Angular CLI

To create a component using the Angular CLI:

1. From a terminal window, navigate to the directory containing your application.


2. Run the ng generate component <component-name> command, where <component-
name> is the name of your new component.

By default, this command creates the following:

 A directory named after the component


 A component file, <component-name>.component.ts
 A template file, <component-name>.component.html
 A CSS file, <component-name>.component.css
 A testing specification file, <component-name>.component.spec.ts

Where <component-name> is the name of your component.

Step 2 - Add the new component to your app's layout

In this step, you add the new component, HomeComponent to your app's root
component, AppComponent, so that it displays in your app's layout.

In the Edit pane of your IDE:


1. Open app.component.ts in the editor.
2. In app.component.ts, (let the component name be home) import HomeComponent by
adding this line to the file level imports.
Import HomeComponent in src/app/app.component.ts

import { HomeComponent } from './home/home.component';

3. In app.component.ts, in @Component, update the imports array property and


add HomeComponent.
Replace in src/app/app.component.ts

imports: [

HomeComponent,

],

4. Save your changes to app.component.ts.


5. In app.component.html, use the component you created just like normal tag.
<app-hello></app-hello>
Check whether the component is imported in main application.
6. If ng serve is running, the app should update. If ng serve is not running, start it again.
7. Check the running app in the browser and confirm that the app has been updated.
Angular Data Binding

Data binding allows Internet users to manipulate web page elements with the help of a web
browser. It includes dynamic HTML and does not require complex programming. Data
binding is used in web applications that contain interactive components such as forms,
calculators, tutorials, and games. The incremental display of a webpage makes data binding
convenient when pages contain an extensive amount of data.
Angular uses the concept of two-way binding. Any UI element-related change is reflected in
the corresponding and specific model state. Conversely, any model state changes reflect in
the UI state. This ensures that the framework is able to connect the DOM to the Model data
with the help of the controller.

Attribute Binding
Attribute binding in Angular helps you bind to HTML attributes of elements in your
template. This can be useful when you want to dynamically update the appearance or
behavior of an element based on some condition. For example, you might want to hide an
element unless a user is logged in, or change the color of an element based on its status. To
bind to an attribute, you use the square brackets around the attribute name.

Class Binding
Angular offers various ways to bind data to HTML elements. Class binding is one of them. It
allows you to dynamically add or remove CSS classes from an element. This can be useful
for applying styles based on certain conditions.
Style Binding
Style binding is a one-way data binding technique that can be used to set the value of a CSS
property on an element. To use style binding, you first need to have a CSS property that you
want to bind to an element.

ngModel
Angular data binding is a two-way process: it can both send and receive data. This means that
when you change something in your view, the model updates automatically, and vice versa.
The ngModel directive makes this two-way data binding possible.
When you use the ngModel directive, you specify a property of the scope as the value of the
directive. This tells Angular to create a two-way binding between the property and the input
control. Any changes to the control are automatically reflected in the model, and any changes
to the model are automatically reflected in the control.

Types of Data Binding

Interpolation Binding
Interpolation is a procedure that allows the user to bind a value to the user interface element.
Interpolation binds the data one-way, which means that data moves in one direction from the
components to HTML elements.

We’ve added the code for the same below.


In the app.component.ts file, we’ve created two properties called name and topic.
export class AppComponent {
title = 'binding';
public name = "Simplilearn"
public topic = "Data Binding"
To interpolate and bind them in the HTML file, type the following code
<h1 style="text-align: center;">Welcome to {{name}}</h1>
<h2 style="text-align: center;">Welcome to the {{topic}} tutorial</h2>
The output will look like this:

Property Binding
Property binding is a one-way data binding mechanism that allows you to set the properties
for HTML elements. It involves updating a property value in the component and binding the
value to an HTML element in the same view. We use property binding for toggle
functionality and sharing data between components. It uses the "[]" syntax for data binding.
In the app.component.ts file, another property is created called image and provided the path
to the Logo in the assets folder.
public image = "/assets/Logo.png"
In the app.component.html file.
<img [src] = "image" alt="" style="height: 100px; width: 250px" class="center">

Event Binding
Event binding type is when information flows from the view to the component when an event
is triggered. The event could be a mouse click or keypress. The view sends the data to update
the component. Unsurprisingly, it is the exact opposite of property binding, where the data
goes from the component to the view.

We have created a Subscribe button that displays a “Thank you” message when clicked on.
<br><button (click)="onClick()">Subscribe to Simplilearn</button></div>
To display the message on the console, we’ve created a function called onClick() in the
app.component.ts file.
onClick(){
console.log("Thanks for subscribing")
}
Every time the user clicks on the button, the message is displayed on the console.
Two-way Data Binding
As the name suggests, two-way binding is a mechanism where data flows from the
component to the view and back. This binding ensures that the component and view are
always in sync. Any changes made on either end are immediately reflected on both. The
general syntax to denote two-way data binding is a combination of Square brackets and
parentheses "[()]".

To illustrate two-way data binding, we’ve created a property with an empty string and an
input box for the user to type. Whatever the user provides is displayed on the screen with the
help of the property.
In the .ts file,
public random = ""
In the .html file, we’ve created an input field
<input [(ngModel)]="random" type="text"> <br>
{{random}}
We have used the ngModel directive and initialized it to random. We’ve then interpolated the
property random.
If we run this code, an error would occur in the console - saying that the ngModel is an
unknown property of the input element. This is due to the fact, that in order to use
the ngModel directive, it's necessary to import the FormsModule. It needs to be imported into
the app.module.ts file:
import { FormsModule } from '@angular/forms';
...
@NgModule({
imports: [
BrowserModule,
FormsModule
]
...
ROUTING ON ANGULAR
In a Single Page Application (SPA), all of our application's functions exist in a single HTML
page. As users access our application's features, the browser needs to render only the parts
that matter to the user, instead of loading a new page. This pattern can significantly improve
your application's user experience.
To define how users navigate through our application, we use routes. Add routes to define
how users navigate from one part of our application to another. We can also configure routes
to guard against unexpected or unauthorized behavior.
Create a sample application
Using the Angular CLI, create a new application, angular-router-sample. This application
will have two components: crisis-list and heroes-list.
1. Create a new Angular project, angular-router-sample.
ng new angular-router-sample
1. When prompted with Would you like to add Angular routing?, select N.
When prompted with Which stylesheet format would you like to use?, select CSS.
After a few moments, a new project, angular-router-sample, is ready.
2. From your terminal, navigate to the angular-router-sample directory.
3. Create a component, crisis-list.
ng generate component crisis-list
4. In your code editor, locate the file, crisis-list.component.html and replace the
placeholder content with the following HTML.
<h3>CRISIS CENTER</h3>
<p>Get your crisis here</p>
5. Create a second component, heroes-list.
ng generate component heroes-list
6. In your code editor, locate the file, heroes-list.component.html and replace the
placeholder content with the following HTML.
<h3>HEROES</h3>
<p>Get your heroes here</p>
7. In your code editor, open the file, app.component.html and replace its contents with
the following HTML.
<h1>Angular Router Sample</h1>
<app-crisis-list></app-crisis-list>
<app-heroes-list></app-heroes-list>
8. Verify that your new application runs as expected by running the ng serve command.
ng serve
9. Open a browser to http://localhost:4200.
You should see a single web page, consisting of a title and the HTML of your two
components.
Define your routes
 The route /crisis-center opens the crisis-center component.
 The route /heroes-list opens the heroes-list component.
A route definition is a JavaScript object. Each route typically has two properties. The first
property, path, is a string that specifies the URL path for the route. The second
property, component, is a string that specifies what component your application should
display for that path.
1. From your code editor, create and open the app.routes.ts file.
2. Create and export a routes list for your application:
import {Routes} from '@angular/router';

export const routes = [];


1. Add two routes for your first two components:
{path: 'crisis-list', component: CrisisListComponent},
{path: 'heroes-list', component: HeroesListComponent},
This routes list is an array of JavaScript objects, with each object defining the properties
of a route.
Import provideRouter from @angular/router
Routing lets you display specific views of your application depending on the URL path. To
add this functionality to your sample application, you need to update the app.config.ts file to
use the router providers function, provideRouter. You import this provider function
from @angular/router.
1. From your code editor, open the app.config.ts file.
Add the following import statements:
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
2. Update the providers in the appConfig:
providers: [provideRouter(routes)]
Update your component with router-outlet
At this point, you have defined two routes for your application. However, your application
still has both the crisis-list and heroes-list components hard-coded in
your app.component.html template. For your routes to work, you need to update your
template to dynamically load a component based on the URL path.
To implement this functionality, you add the router-outlet directive to your template file.
1. From your code editor, open the app.component.html file.
2. Delete the following lines.
<app-crisis-list></app-crisis-list>
<app-heroes-list></app-heroes-list>
3. Add the router-outlet directive.
<router-outlet></router-outlet>
4. Add RouterOutlet to the imports of the AppComponent in app.component.ts
imports: [RouterOutlet],
View your updated application in your browser. You should see only the application
title. To view the crisis-list component, add crisis-list to the end of the path in your
browser's address bar. For example:
http://localhost:4200/crisis-list
Notice that the crisis-list component displays. Angular is using the route you defined
to dynamically load the component. You can load the heroes-list component the same
way:
http://localhost:4200/heroes-list
Control navigation with UI elements
Currently, your application supports two routes. However, the only way to use those
routes is for the user to manually type the path in the browser's address bar. In this
section, you'll add two links that users can click to navigate between the heroes-
list and crisis-list components.
1. Open the app.component.html file and add the following HTML below the
title.
<nav>
<a class="button" routerLink="/crisis-list">Crisis Center</a> |
<a class="button" routerLink="/heroes-list">Heroes</a>
</nav>
2. This HTML uses an Angular directive, routerLink. This directive connects the routes
you defined to your template files.
3. Add the RouterLink directive to the imports list
of AppComponent in app.component.ts.
4. Open the app.component.css file and add the following styles.
.button {
box-shadow: inset 0 1px 0 0 #ffffff;
background: #ffffff linear-gradient(to bottom, #ffffff 5%, #f6f6f6 100%);
border-radius: 6px;
border: 1px solid #dcdcdc;
display: inline-block;
cursor: pointer;
color: #666666;
font-family: Arial, sans-serif;
font-size: 15px;
font-weight: bold;
padding: 6px 24px;
text-decoration: none;
text-shadow: 0 1px 0 #ffffff;
outline: 0;
}
.activebutton {
box-shadow: inset 0 1px 0 0 #dcecfb;
background: #bddbfa linear-gradient(to bottom, #bddbfa 5%, #80b5ea 100%);
border: 1px solid #84bbf3;
color: #ffffff;
text-shadow: 0 1px 0 #528ecc;
}
If you view your application in the browser, you should see these two links. When
you click on a link, the corresponding component appears.
Identify the active route
While users can navigate your application using the links you added in the previous section,
they don't have a straightforward way to identify what the active route is. Add this
functionality using Angular's routerLinkActive directive.
1. From your code editor, open the app.component.html file.
2. Update the anchor tags to include the routerLinkActive directive.
<nav>
<a class="button"
routerLink="/crisis-list"
routerLinkActive="activebutton"
ariaCurrentWhenActive="page">
Crisis Center
</a> |
<a class="button"
routerLink="/heroes-list"
routerLinkActive="activebutton"
ariaCurrentWhenActive="page">
Heroes
</a>
</nav>
3. Add the RouterLinkActive directive to the imports list
of AppComponent in app.component.ts.
View your application again. As you click one of the buttons, the style for that button
updates automatically, identifying the active component to the user. By adding
the routerLinkActive directive, you inform your application to apply a specific CSS
class to the active route.
Adding a redirect
In this step, you add a route that redirects the user to display the /heroes-list component.
1. From your code editor, open the app.routes.ts file.
2. Update the routes section as follows.

{path: '', redirectTo: '/heroes-list', pathMatch: 'full'},


This new route uses an empty string as its path. In addition, it replaces
the component property with two new ones:

PROPERTIE
DETAILS
S

This property instructs Angular to redirect from an empty path to


redirectTo the heroes-list path.

pathMatch This property instructs Angular on how much of the URL to


PROPERTIE
DETAILS
S

match. For this tutorial, you should set this property to full. This
strategy is recommended when you have an empty string for a
path.

Now when you open your application, it displays the heroes-list component by
default.

Adding a 404 page


It is possible for a user to try to access a route that you have not defined. To account
for this behavior, the best practice is to display a 404 page. In this section, you'll
create a 404 page and update your route configuration to show that page for any
unspecified routes.
1. From the terminal, create a new component, PageNotFound.
ng generate component page-not-found
2. From your code editor, open the page-not-found.component.html file and
replace its contents with the following HTML.
<h2>Page Not Found</h2>
<p>We couldn't find that page! Not even with x-ray vision.</p>
3. Open the app.routes.ts file and add the following route to the routes list:
{path: '**', component: PageNotFoundComponent}
The new route uses a path, **. This path is how Angular identifies a wildcard route.
Any route that does not match an existing route in your configuration will use this
route.
The wildcard route is placed at the end of the array. The order of your routes is
important, as Angular applies routes in order and uses the first match it finds.
Directives
Directives are classes that add additional behavior to elements in your Angular applications.

The different types of Angular directives are as follows:

DIRECTIVE
DETAILS
TYPES

Used with a template. This type of directive is the most


Components common directive type.
DIRECTIVE
DETAILS
TYPES

Change the appearance or behavior of an element, component,


Attribute directives or another directive.

Change the DOM layout by adding and removing DOM


Structural directives elements.

Built-in attribute directives

Attribute directives listen to and modify the behavior of other HTML elements, attributes,
properties, and components.

Many attribute directives are defined through modules such as


the CommonModule, RouterModule and FormsModule.

The most common attribute directives are as follows:

COMMON DIRECTIVES DETAILS

NgClass Adds and removes a set of CSS classes.

NgStyle Adds and removes a set of HTML styles.

NgModel Adds two-way data binding to an HTML form element.


Attribute directives
Change the appearance or behavior of DOM elements and Angular components with attribute
directives.
Building an attribute directive

This section is used to create a highlight directive that sets the background color of the host
element to yellow.

1. To create a directive, use the CLI command ng generate directive.


ng generate directive highlight
The CLI creates src/app/highlight.directive.ts, a corresponding test
file src/app/highlight.directive.spec.ts, and declares the directive class in the AppModule.
The CLI generates the default src/app/highlight.directive.ts.
The @Directive() decorator's configuration property specifies the directive's CSS attribute
selector, [appHighlight].
2. Import ElementRef from @angular/core. ElementRef grants direct access to the host
DOM element through its nativeElement property.
3. Add ElementRef in the directive's constructor() to inject a reference to the host DOM
element, the element to which you apply appHighlight.
4. Add logic to the HighlightDirective class that sets the background to yellow.

import {Directive, ElementRef} from '@angular/core';

@Directive({
standalone: true,
selector: '[appHighlight]',
})
export class HighlightDirective {
constructor(private el: ElementRef) {
this.el.nativeElement.style.backgroundColor = 'yellow';
}
}
Applying an attribute directive
To use the HighlightDirective, add a <p> element to the HTML template with the directive as
an attribute.
<p appHighlight>Highlight me!</p>
Angular creates an instance of the HighlightDirective class and injects a reference to
the <p> element into the directive's constructor, which sets the <p> element's background
style to yellow.
Handling user events

This section shows you how to detect when a user mouses into or out of the element and to
respond by setting or clearing the highlight color.

1. Import HostListener from '@angular/core'.

In src/app/highlight.directive.ts (imports)
import {Directive, ElementRef, HostListener} from '@angular/core';
2. Add two event handlers that respond when the mouse enters or leaves, each with
the @HostListener() decorator.
@HostListener('mouseenter') onMouseEnter() {
this.highlight('yellow');
}

@HostListener('mouseleave') onMouseLeave() {
this.highlight('');
}

private highlight(color: string) {


this.el.nativeElement.style.backgroundColor = color;
}
The background color appears when the pointer hovers over the paragraph element
and disappears as the pointer moves out.

Structural directives

In Angular, structural directives are a type of directive that alter the


structure of the DOM by adding, removing, or manipulating elements.
They are called "structural" because they deal with the structure of the
DOM by adding or removing elements based on certain conditions. Unlike
attribute directives, which only change the appearance or behavior of an
element, structural directives actually change the structure of the DOM.

ngIf

The ngIf directive is used to conditionally render or remove elements from


the DOM based on a given expression.
<div *ngIf="condition; else elseBlock">
<!-- Content to display when condition is true -->
<p>This content is displayed when the condition is true.</p>
</div>

<ng-template #elseBlock>
<!-- Content to display when condition is false -->
<p>This content is displayed when the condition is false.</p>
</ng-template>

In this example:

 The *ngIf="condition" attribute is applied to a div element. If


condition is true, the content inside the div is displayed; otherwise,
it is hidden.
 The else elseBlock part is used to define the content that should be
displayed when the condition is false. This is done using an ng-
template with the local reference #elseBlock .
 The content inside the ng-template is what will be displayed when
the condition is false.

We can also have templates for both the conditions as below:

<div *ngIf="isFirstName; then firstName else lastName">

</div>
<ng-template #firstName>
<h2>Sutha</h2>
</ng-template>
<ng-template #lastName>
<h2>Balakumar</h2>
</ng-template>

ngSwitch

In Angular, the ngSwitch directive is used for conditionally rendering


content based on the value of an expression. It's particularly useful when
you have multiple possible values for a variable and want to display
different content for each value. The syntax involves using ngSwitch in
combination with ngSwitchCase and optionally ngSwitchDefault. Here's
a breakdown of how to use the ngSwitch syntax:

In component’s html, use the following:

<div [ngSwitch]="expression">
<div *ngSwitchCase="value1">Content for value1</div>
<div *ngSwitchCase="value2">Content for value2</div>
<!-- Add more ngSwitchCase as needed -->
<div *ngSwitchDefault>Default content if no match</div>
</div>

 [ngSwitch]="expression" binds the value of expression to ngSwitch.


 *ngSwitchCase="value1" checks if expression equals value1. If true,
it renders the content inside that block.
 You can have multiple *ngSwitchCase blocks for different values.
 *ngSwitchDefault is optional and provides content to be displayed
when none of the *ngSwitchCase values match expression.

Example:
<div [ngSwitch]="status">
<div *ngSwitchCase="'active'">Status is Active</div>
<div *ngSwitchCase="'inactive'">Status is Inactive</div>
<div *ngSwitchCase="'pending'">Status is Pending</div>
<div *ngSwitchDefault>Unknown Status</div>
</div>
Here, assuming status is a variable in your component, the content inside
the appropriate *ngSwitchCase block will be displayed based on the value
of status.

ngFor
In Angular, the ngFor directive is used for rendering a set of elements for
each item in an iterable list. It allows you to iterate over a collection (such
as an array or an object) and generate HTML content for each item.
we have an array of fruits in an Angular component, and we want to use
the ngFor directive to iterate over the array and display each fruit in a list.
// fruit-list.component.ts

@Component({
selector: 'app-fruit-list',

})
export class FruitListComponent {
fruits = ['Apple', 'Banana', 'Orange', 'Mango'];
}

In component’s html, include the following:

<h2>Fruit List</h2>
<ul>
<li *ngFor="let fruit of fruits">{{ fruit }}</li>
</ul>
Typescript Vs Javascript
TypeScript and JavaScript are both programming languages, but they
have some key differences:

1. Static Typing:
 JavaScript: It is a dynamically typed language, meaning you
don't have to explicitly declare the data type of a variable.
The type of a variable can change during runtime.
 TypeScript: It is a statically typed superset of JavaScript,
which means that you can declare the type of a variable at
compile-time. TypeScript introduces static typing, providing a
way to catch errors during development.
2. Compilation:
 JavaScript: It is an interpreted language that is executed by
the browser or another JavaScript runtime environment.
 TypeScript: It needs to be transpiled into JavaScript before
execution. TypeScript code is written in a higher level of
abstraction and is compiled to JavaScript.
3. Object-Oriented Features:
 JavaScript: It is prototype-based and supports object-
oriented programming using prototypes and constructor
functions.
 TypeScript: It is designed with optional static typing and
includes features such as classes, interfaces, modules, and
other constructs commonly found in object-oriented
languages.
4. Tooling and IDE Support:
 JavaScript: It has good tooling and support in various IDEs
(Integrated Development Environments) and text editors.
 TypeScript: Because of its static typing, TypeScript provides
better tooling support. Features like autocompletion, code
navigation, and error checking are more robust in TypeScript.
5. Compatibility:
 JavaScript: Code written in JavaScript is compatible with all
major browsers and environments that support ECMAScript
standards.
 TypeScript: TypeScript code needs to be transpiled to
JavaScript, and the resulting JavaScript code is compatible
with any environment that supports ECMAScript standards.
6. Null and Undefined:
 JavaScript: Variables can be null or undefined .
 TypeScript: With strict null checks enabled, TypeScript
introduces a type null and undefined that can be explicitly
assigned to variables.
7. Enums:
 JavaScript: Does not have built-in support for enums.
 TypeScript: Supports enums, making it easier to work with a
set of named constants.
8. Modules:
 JavaScript: Uses a variety of module systems, including
CommonJS and AMD, but does not have built-in support for
modules until the introduction of ECMAScript modules (ES6).
 TypeScript: Supports ECMAScript modules as well as its own
module system, making it easier to organize and reuse code.

In summary, TypeScript is a superset of JavaScript, adding static typing


and other features, making it a more powerful and maintainable language
for larger codebases and complex applications. However, JavaScript
remains the universal language for web development and is supported in
all major browsers.
Appendix
TypeScript Arrays
TypeScript has a specific syntax for typing arrays.
const names: string[] = [];
names.push("Dylan"); // no error
// names.push(3); // Error: Argument of type 'number' is not assignable to parameter of type
'string'.
Readonly
The readonly keyword can prevent arrays from being changed.
Example
const names: readonly string[] = ["Dylan"];
names.push("Jack"); // Error: Property 'push' does not exist on type 'readonly string[]'.
// try removing the readonly modifier and see if it works?
Type Inference
TypeScript can infer the type of an array if it has values.
Example
const numbers = [1, 2, 3]; // inferred to type number[]
numbers.push(4); // no error
// comment line below out to see the successful assignment
numbers.push("2"); // Error: Argument of type 'string' is not assignable to parameter of type
'number'.
let head: number = numbers[0]; // no error
TypeScript Functions
TypeScript has a specific syntax for typing function parameters and return values.
Return Type
The type of the value returned by the function can be explicitly defined.
Example
// the `: number` here specifies that this function returns a number
function getTime(): number {
return new Date().getTime();
}
If no return type is defined, TypeScript will attempt to infer it through the types of the
variables or expressions returned.
Void Return Type
The type void can be used to indicate a function doesn't return any value.
Example
function printHello(): void {
console.log('Hello!');
}
Parameters
Function parameters are typed with a similar syntax as variable declarations.
Example
function multiply(a: number, b: number) {
return a * b;
}
If no parameter type is defined, TypeScript will default to using any
Optional Parameters
By default TypeScript will assume all parameters are required, but they can be explicitly
marked as optional.
Example
// the `?` operator here marks parameter `c` as optional
function add(a: number, b: number, c?: number) {
return a + b + (c || 0);
}
Default Parameters
For parameters with default values, the default value goes after the type annotation:
Example
function pow(value: number, exponent: number = 10) {
return value ** exponent;
}
TypeScript can also infer the type from the default value.

Named Parameters
Typing named parameters follows the same pattern as typing normal parameters.
Example
function divide({ dividend, divisor }: { dividend: number, divisor: number }) {
return dividend / divisor;
}
Rest Parameters
Rest parameters can be typed like normal parameters, but the type must be an array as rest
parameters are always arrays.
Example
function add(a: number, b: number, ...rest: number[]) {
return a + b + rest.reduce((p, c) => p + c, 0);
}
Type Alias
Function types can be specified separately from functions with type aliases.
Example
type Negate = (value: number) => number;

// in this function, the parameter `value` automatically gets assigned the type `number` from
the type `Negate`
const negateFunction: Negate = (value) => value * -1;
TypeScript Classes
TypeScript adds types and visibility modifiers to JavaScript classes.
Members: Types
The members of a class (properties & methods) are typed using type annotations, similar to
variables.
Example
class Person {
name: string;
}

const person = new Person();


person.name = "Jane";
Members: Visibility
Class members also be given special modifiers which affect visibility.
There are three main visibility modifiers in TypeScript.
 public - (default) allows access to the class member from anywhere
 private - only allows access to the class member from within the class
 protected - allows access to the class member from itself and any classes that inherit it
 Example
 class Person {
private name: string;

public constructor(name: string) {


this.name = name;
}

public getName(): string {


return this.name;
}
}
const person = new Person("Jane");
console.log(person.getName()); // person.name isn't accessible from outside the class
since it's private
Parameter Properties
TypeScript provides a convenient way to define class members in the constructor, by adding
a visibility modifiers to the parameter.
Example
class Person {
// name is a private member variable
public constructor(private name: string) {}

public getName(): string {


return this.name;
}
}

const person = new Person("Jane");


console.log(person.getName());
Readonly
Similar to arrays, the readonly keyword can prevent class members from being changed.
Example
class Person {
private readonly name: string;

public constructor(name: string) {


// name cannot be changed after this initial definition, which has to be either at it's
declaration or in the constructor.
this.name = name;
}

public getName(): string {


return this.name;
}
}

const person = new Person("Jane");


console.log(person.getName());
Inheritance: Implements
Interfaces can be used to define the type a class must follow through
the implements keyword.
Example
interface Shape {
getArea: () => number;
}

class Rectangle implements Shape {


public constructor(protected readonly width: number, protected readonly height: number) {}
public getArea(): number {
return this.width * this.height;
}
}
A class can implement multiple interfaces by listing each one after implements, separated by
a comma like so: class Rectangle implements Shape, Colored {
Inheritance: Extends
Classes can extend each other through the extends keyword. A class can only extends one
other class.
Example
interface Shape {
getArea: () => number;
}

class Rectangle implements Shape {


public constructor(protected readonly width: number, protected readonly height: number) {}

public getArea(): number {


return this.width * this.height;
}
}

class Square extends Rectangle {


public constructor(width: number) {
super(width, width);
}

// getArea gets inherited from Rectangle


}

Override
When a class extends another class, it can replace the members of the parent class with the
same name.
Newer versions of TypeScript allow explicitly marking this with the override keyword.
Example
interface Shape {
getArea: () => number;
}

class Rectangle implements Shape {


// using protected for these members allows access from classes that extend from this class,
such as Square
public constructor(protected readonly width: number, protected readonly height: number) {}

public getArea(): number {


return this.width * this.height;
}
public toString(): string {
return `Rectangle[width=${this.width}, height=${this.height}]`;
}
}

class Square extends Rectangle {


public constructor(width: number) {
super(width, width);
}

// this toString replaces the toString from Rectangle


public override toString(): string {
return `Square[width=${this.width}]`;
}
}

By default the override keyword is optional when overriding a method, and only helps to
prevent accidentally overriding a method that does not exist. Use the
setting noImplicitOverride to force it to be used when overriding.

Abstract Classes
Classes can be written in a way that allows them to be used as a base class for other classes
without having to implement all the members. This is done by using the abstract keyword.
Members that are left unimplemented also use the abstract keyword.
Example
abstract class Polygon {
public abstract getArea(): number;

public toString(): string {


return `Polygon[area=${this.getArea()}]`;
}
}

class Rectangle extends Polygon {


public constructor(protected readonly width: number, protected readonly height: number) {
super();
}

public getArea(): number {


return this.width * this.height;
}
}

Abstract classes cannot be directly instantiated, as they do not have all their members
implemented.

You might also like