TypeScript
TypeScript
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.
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
====================
For example, to create a variable that can hold either null or a number, use the
following notation:
--------------------------------------
let numberOrNull: number | null;
When declaring variables, TypeScript uses let and const keywords from modern
JavaScript:
===================
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:
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.
===================
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.
-------------------------------------------
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:
-------------------------------------------
===================
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:
================
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
--------------------------------------------------------
const isHome = true;
const inPajamas = false;
const wantsToEat = false;
const isBored = false;
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.
--------------------------------------------------------
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;