0% found this document useful (0 votes)
2 views11 pages

TypeScript

TypeScript is a strict syntactical superset of JavaScript that adds optional static typing, helping developers catch errors early in the development process. It supports modern ECMAScript features and allows for type-safe variable declarations, functions, and classes. Key features include basic types, arrays, loops, operators, control flow, and interfaces, making TypeScript a powerful tool for building robust applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views11 pages

TypeScript

TypeScript is a strict syntactical superset of JavaScript that adds optional static typing, helping developers catch errors early in the development process. It supports modern ECMAScript features and allows for type-safe variable declarations, functions, and classes. Key features include basic types, arrays, loops, operators, control flow, and interfaces, making TypeScript a powerful tool for building robust applications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 11

TypeScript is a strict syntactical superset of JavaScript, adding optional static

typing. Developed and maintained by Microsoft, it allows developers to use the


latest ECMAScript features and compile the code to plain JavaScript, which can be
run in any browser or Node.js environment.

The major advantage of using TypeScript is its static typing feature, which helps
catch errors early during the development phase. This can be invaluable for larger
projects where catching bugs early can save a significant amount of time and money.

npm install -g typescript

The most basic program: "Hello World". In TypeScript, just like JavaScript, this
can be done with a simple console.log() statement.

----------------------------------------
const message: string = "Hello World";
console.log(message);
----------------------------------------

The : string is a type annotation that tells TypeScript that the message variable
can only hold a string.

TypeScript also supports formatting strings using the backtick operator. Here is an
example:

----------------------------------------
const name = "John";
const message: string = `Hello ${name}`;
console.log(message);
----------------------------------------
This prints "Hello John", because the name variable was formatted into the string
right after the word Hello.

====================
Variables and Types
====================

In TypeScript, variables are containers for storing data values.


TypeScript enhances variables with type annotations, allowing you to enforce the
type of data your variables can hold.
This helps in catching type-related errors early in the development process, making
your code more robust and maintainable.

There are several basic types in TypeScript, including:

number: For numeric values.


string: For textual data.
boolean: For true/false values.
any: A wildcard type that can be anything.
arrays: For collections of values, denoted by Type[] or Array<Type>.

Defining a variable is done in TypeScript can be done either using a type or


omitting it.
If omitted, the interpreter will set the type according to the type of variable it
was defined with.
---------------------------------------------------
let name: string = "John";
let age: number = 25;
let hobbies: string[] = ["Basketball", "Hockey"];

let stringOrNumber = "this is a string!";


console.log(typeof stringOrNumber); // string
---------------------------------------------------
TypeScript has a very strong typing system.
One of the more useful features of it is that it allows you to define a variable to
hold a specific range of types.

For example, to create a variable that can hold either null or a number, use the
following notation:
--------------------------------------
let numberOrNull: number | null;

// these assignments will work


numberOrNull = 3;
numberOrNull = null;

// this is not allowed in TypeScript


numberOrNull = "invalid assignment";
--------------------------------------

When declaring variables, TypeScript uses let and const keywords from modern
JavaScript:

let: Declares a block-scoped variable, optionally initializing it to a value. let


variables can be reassigned.
const: Declares a block-scoped constant. Once assigned, const variables cannot be
reassigned.

===================
Declaring Variables
===================

Using let:

When you use let, you're telling TypeScript that the variable may change its value
over time. For example:
-------------------------------------------
let age: number = 25;
age = 26; // This is allowed with `let`.
------------------------------------------

Using const:

With const, the variable must be initialized at the time of declaration, and it
cannot be reassigned later. This is useful for values that should not change
throughout the application.

-------------------------------------------
const pi: number = 3.14;
pi = 3.15; // This would be an error because `pi` is a constant.
-------------------------------------------
===================
Types
===================
TypeScript is statically typed. This means that the type of a variable is known at
compile time. This is different from JavaScript, where types are understood
dynamically at runtime.
===================
Basic Types
===================
Here are some basic types in TypeScript:

Number: All numbers in TypeScript are floating-point values or BigIntegers. These


can be integers, decimals, etc.

let decimal: number = 6;


let hex: number = 0xf00d;
let binary: number = 0b1010;
let octal: number = 0o744;

String: Represents a sequence of characters. TypeScript, like JavaScript, uses


double quotes (") or single quotes (') to surround string data.

let color: string = "blue";


color = 'red'; // Both single and double quotes are acceptable.

Boolean: The most basic datatype is the simple true/false value.


let isDone: boolean = false;

Any: It can be any type of value. It is useful when you don't want to write a
specific type, but its use should be limited to when you really don't know what
type there will be.

let notSure: any = 4;


notSure = "maybe a string instead";
notSure = false;

Exercise:Given the provided code, identify the errors in variable declarations


based on TypeScript types and fix them.
let count: number = "five";
const isActive: boolean = 1;
let items: number[] = 10;
console.log(count, isActive, items);

===================
Functions
===================
Functions in TypeScript can have typed parameters and return values.

In the following example, the function add receives two numbers and returns a
number. The function defines the types of the parameters and its return value using
the : operator.

-------------------------------------------

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


return a + b;
}

Arrow functions
Functions can also be defined as variables using the "arrow function" notation:
const add = (a: number, b: number): number => {
return a + b;
}
-------------------------------------------

Arrow functions also support a shorter form - if the function is an expression and
not a code block denoted using curly braces, it will return that expression as the
output of the function.

-------------------------------------------
For example:

const add = (a: number, b: number): number => a + b;

-------------------------------------------

===================
Loops
===================
Looping is a foundational concept in programming, allowing for repeated execution
of a block of code. TypeScript, building upon JavaScript, offers a variety of loop
constructs to handle different scenarios. This tutorial will delve into the primary
loop mechanisms in TypeScript, discussing their syntax and use cases.
===================
for Loop:
===================
The traditional for loop is composed of an initializer, a condition, and an
increment expression. It's perfect for cases where you know in advance how many
iterations you need.
-------------------------------------------
for (let i = 0; i < 5; i++) {
console.log(i);
}
-------------------------------------------
This prints numbers 0 through 4.

===================
for...of Loop
===================

Ideal for iterating over elements in arrays or other iterable objects, the for...of
loop offers simplicity.
-------------------------------------------
const fruits = ['apple', 'banana', 'cherry'];
for (let fruit of fruits) {
console.log(fruit);
}
-------------------------------------------
This prints 'apple', 'banana', and 'cherry'.
===================
for...in Loop
===================
This loop iterates over the properties (keys) of an object, making it suitable for
object property traversal.
-------------------------------------------
const person = {
name: "John",
age: 30,
city: "New York"
};
for (let key in person) {
console.log(key, person[key]);
}
-------------------------------------------
This prints 'name John', 'age 30', and 'city New York'.
==========================
while and do...while Loops
==========================
The while loop continues executing its block as long as its condition remains true.
On the other hand, the do...while loop ensures the block gets executed at least
once before checking the condition.
-------------------------------------------
let count = 0;
while (count < 3) {
console.log(count);
count++;
}
var n:number = 10;
do {
console.log(n);
n--;
} while(n>=0);
-------------------------------------------
This prints numbers 0, 1, and 2.
==========================
Arrays
==========================
Arrays serve as one of the primary data structures in TypeScript and JavaScript. In
TypeScript, they offer the added advantage of type safety, ensuring that once an
array is defined to hold a particular type of data, it will always maintain that
type.
==========================
Defining Arrays
==========================
Arrays can be defined in TypeScript using either the array type syntax or the
generic array type:
-------------------------------------------
let names: string[] = ["Alice", "Bob", "Charlie"];
let ids: Array<number> = [101, 102, 103];
-------------------------------------------
==========================
Adding and Removing Elements
==========================
Arrays offer several methods to add or remove items:

push(): Adds one or more elements to the end of an array.


unshift(): Inserts one or more elements at the beginning.
pop(): Removes the last element.
shift(): Removes the first element.
-----------------------------------------------------------------
Example:
let colors: string[] = ["red", "blue"];
colors.push("yellow"); // ["red", "blue", "yellow"]
colors.unshift("green"); // ["green", "red", "blue", "yellow"]
colors.pop(); // ["green", "red", "blue"]
colors.shift(); // ["red", "blue"]
---------------------------------------------------------------
===============================
Accessing and Modifying Elements
===============================
Array elements can be accessed using their index, starting from 0. They can also be
modified using their index.
---------------------------------------------------------
let fruits: string[] = ["apple", "orange", "grape"];
console.log(fruits[1]); // "orange"
fruits[1] = "banana"; // ["apple", "banana", "grape"]
--------------------------------------------------------

================
Finding Elements
================
You can search for an element using indexOf() or check its existence with
includes().
--------------------------------------------------------
let pets: string[] = ["cat", "dog", "bird"];
console.log(pets.indexOf("cat")); // 0
console.log(pets.indexOf("dog")); // 1
console.log(pets.includes("fish")); // false
--------------------------------------------------------
Notice that arrays in TypeScript, like in many other languages, have zero-based
indices.
================
Array Length
================
The length property provides the number of elements in an array.
--------------------------------------------------------
let digits: number[] = [1, 2, 3, 4, 5];
console.log(digits.length); // 5
--------------------------------------------------------
================
Tuples
================

Tuples in TypeScript allow you to express an array where the type of a fixed number
of elements is known but does not have to be the same. You can define a tuple as:
-------------------------------------------
let x: [string, number];
x = ["hello", 10]; // OK
console.log(x[0])
x = [10, "hello"]; // Error
-------------------------------------------

================
Operators
================
Operators in TypeScript are fundamental elements that allow you to perform various
operations on your data. This can range from simple arithmetic calculations to more
complex logical evaluations and comparisons. Understanding these operators is
essential to writing robust and efficient TypeScript code.
================
Arithmetic Operators
================
Arithmetic operators allow you to perform mathematical operations between numbers.
--------------------------------------------------------
Addition (+): Adds two numbers.
const sum: number = 5 + 3; // 8

Subtraction (-): Subtracts one number from another.


const difference: number = 8 - 5; // 3

Multiplication (*): Multiplies two numbers.


const product: number = 4 * 7; // 28

Division (/): Divides one number by another.


const quotient: number = 20 / 4; // 5

Modulus (%): Returns the remainder of a division.


const remainder: number = 11 % 3; // 2
--------------------------------------------------------
=================
Logical Operators
=================
Logical operators allow you to combine multiple conditions.

AND (&&): Returns true if both conditions are true.


OR (||): Returns true if at least one of the conditions is true.
NOT (!): Reverses the truthiness of the condition.
Logical operators allow you to create a complex boolean expression, for example:

--------------------------------------------------------
const isHome = true;
const inPajamas = false;
const wantsToEat = false;
const isBored = false;

// I should go outside if I am home, not in my pajamas, and


// either I want to eat or I am bored
const shouldGoOutside = isHome && !inPajamas && (wantsToEat || isBored);
--------------------------------------------------------v

Operators are vital tools in TypeScript that enable various operations. They offer
great flexibility in processing and evaluating data, making your coding experience
efficient and expressive. Familiarizing yourself with these operators will
significantly boost your TypeScript proficiency.

=====================
Comparison Operators
=====================
Comparison operators allow you to compare two values.

Equal to (==): Checks if two values are equal.


Not equal to (!=): Checks if two values are not equal.
Strictly equal to (===): Checks if two values are equal in value and type.
Strictly not equal to (!==): Checks if two values are not equal in value and type.
Greater than (>): Checks if the value on the left is greater than the value on the
right.
Less than (<): Checks if the value on the left is less than the value on the right.
Greater than or equal to (>=): Checks if the value on the left is greater than or
equal to the value on the right.
Less than or equal to (<=): Checks if the value on the left is less than or equal
to the value on the right.
For example, to check if a number is between 3 and 7, we can write:

--------------------------------------------------------
const number = 5;
const between = number > 5 && number < 7;
const numberIsNotZero = number !== 0;
--------------------------------------------------------
=====================
Control Flow
=====================
if..else

Using an if..else statement allows you to make a choice based on the result of a
boolean expression:
-------------------------------------------------------
const age = 20;
if (age === 20) {
// execute when true
}
if (age === 20) {
// execute when true
} else {
// execute when false
}
if (age === 20) {
// execute when true
} else if (age < 20) {
// execute when age is less than 20
} else {
// execute when age is greater than 20
}
-------------------------------------------------------
switch
const n = 3;
switch (n) {
case 1:
// execute when n is 1
break;
case 2:
// execute when n is 2
break;
case 3:
// execute when n is 3
// FALL THROUGH
case 4:
// execute when n is 3 or 4
break;
default:
// execute for all other numbers
}

-------------------------------------------------------
=====================
Classes
=====================
Classes are a way to define blueprints for objects. They encapsulate data and
behavior
and can be used to create instances of objects with predefined properties and
methods.
Classes can be extended and inherited, allowing for the creation of complex object
hierarchies.
-------------------------------------------------------
class Dimension {
// Private properties can only be accessed
// by this class:
private length: number;
// Protected properties can be accessed by
// this class and any subclasses:
protected width: number;
// Public properties can be accessed by anything:
public height: number;
// We can set the initial values in the constructor:
constructor(l: number, w: number, h: number) {
this.length = l;
this.width = w;
this.height = h;
}
// class method
getLength(): number {
return this.length;
}
}
const box = new Dimension(3, 2, 1);
// call method:
box.getLength(); // 3
-------------------------------------------------------
TypeScript Inheritance
-------------------------------------------------------
class Car {
Color:string
constructor(color:string) {
this.Color = color
}
}
class Audi extends Car {
Price: number
constructor(color: string, price: number) {
super(color);
this.Price = price;
}
display():void {
console.log("Color of Audi car: " + this.Color);
console.log("Price of Audi car: " + this.Price);
}
}
let obj = new Audi(" Black", 8500000 );
obj.display();
-------------------------------------------------------

=====================
Interfaces
=====================
Interfaces provide a way to define the shape of objects or classes. They define the
contracts that objects must follow, specifying the properties and methods that an
object
must have. Interfaces make it easier to write type-safe code by providing a way to
ensure that objects are of the correct shape before they are used in a program.
They
also allow for code to be more modular and reusable, since objects can be easily
swapped out as long as they adhere to the interface's contract.
-------------------------------------------------------
interface Area {
area(): number;
}
interface Perimeter {
perimeter(): number;
}
// OK to implement more than one interface
class Rectangle implements Area, Perimeter {
constructor(
public length: number,
public width: number,
) {}
// We must provide an `area` function:
area(): number {
return this.length * this.width;
}
// We must provide a `perimeter` function:
perimeter(): number {
return 2 * (this.length + this.width);
}
-------------------------------------------------------
========
Unions
========
Union types allows you to declare a variable or parameter that can hold multiple
types
of value and are declared using the pipe symbol ( | ) between the types. Union
types
can be useful when you want something to accept multiple types of input.
-------------------------------------------------------
// make a new union type
type Color = "red" | "green" | "blue";
// only "red" "green" or "blue" is allowed here:
const r: Color = "red";
const r: Color = "yellow"; // ERROR: "yellow" not in type Color
function setBgColor(c: Color) {
// type guard
switch (c) {
case "red":
break;
case "green":
break;
case "blue":
break;
}
}
-------------------------------------------------------
==================
Generic Functions
==================
Generic functions are functions that are designed to work with different types of
data.
They allow you to create a function that can be used with various types of data
without
having to write a separate function for each type. This makes your code more
efficient,
reusable, and easier to maintain. Generic functions are especially useful when
working
with collections of data, such as arrays, because they allow you to create a
function that
can work with any type of data in the collection.
// generic type T will be replaced with whatever
// type is used with the function
function getFirst<T>(arr: T[]): T | undefined {
if (arr.length > 0) {
return arr[0];
}
return undefined;
}
const nums = [1, 2, 3];
const one = getFirst(nums); // T is `number`
const letters = ["a", "b", "c"];
const a = getFirst(letters); // T is `string`
assert.equal(a, "a");
const objects = [{ first: 1 }, { second: 2 }];
const first = getFirst(objects); // T is `object`
-------------------------------------------------------
Generic Classes
Generic classes offer the ability to define a class that can work with a variety of
different
data types. By using generic type parameters, you can create a single class that
can be
customized to work with any type of data that you need.
Similarly to generic functions, generic classes allow you to write more flexible
and
reusable code, since you don't have to create a separate class for every possible
data
type
-------------------------------------------------------

// generic class
class Box<T> {
// member variable
val: T;

// constructor with value


constructor(value: T) {
this.val = value;
}

// Method to get value


get(): T {
return this.val;
}

// Method to set value


set(value: T): void {
this.val = value;
}
}

// create object of Box class


let box1 = new Box<number>(10);
console.log(box1.get()); // 10

let box2 = new Box<string>("Hello");


console.log(box2.get()); // Hello
-------------------------------------------------------

You might also like