Angular Typescript
Angular Typescript
Understand basic types like string, number, boolean, null, undefined, and symbol.
Array
let numbers: number[] = [1, 2, 3, 4]; // array of numbers let strings: Array<string> = ["apple",
"banana", "cherry"]; // array of strings
let person: [string, number] = ["John", 30]; // tuple with string and number let point: [number,
number] = [10, 20]; // tuple with two numbers
// You can add more elements at the end if you define the tuple to accept additional values (like
`...boolean[]`)
user.push(false);
1.3 Enums
Examples –
Numeric Enum
enum Direction {
Up, // 0
Down, // 1
Left, // 2
Right // 3
console.log(Direction.Up); // Output: 0
console.log(Direction.Left); // Output: 2
enum StatusCode {
OK = 200,
NotFound = 404,
InternalServerError = 500
}
String Enums
enum UserRole {
Admin = "ADMIN",
User = "USER",
Guest = "GUEST"
enum FileAccess {
Read = 1,
Write,
Execute,
console.log(FileAccess.Read); // Output: 1
console.log(FileAccess.ReadWrite); // Output: 3 (1 | 2)
unknown Type
similar to any but, you cannot perform operations on an unknown type unless you first assert or
narrow its type
Void
console.log(message);
never
A function with a return type of never will either:
while (true) {
2.1 Interface
interface Product {
name: "Laptop",
price: 1000,
category: "Electronics",
applyDiscount() {
if (this.discount) {
} else {
};
name: "Phone",
price: 500,
category: "Electronics",
applyDiscount() {
if (this.discount) {
} else {
console.log("No discount available.");
};
a type alias is a way to create a custom name for a type. A type alias is similar to an interface, but it is
more flexible in the types it can represent.
Declaration
// 1. Type Alias for a Primitive Type
type Person = {
name: string;
age: number;
greet(): void;
};
name: "John",
age: 30,
greet() {
};
1. Basic Function Type: Defines function signature with parameters and return type.
return a + b;
return a - b;
};
// 3. Arrow Function
return a * b;
};
return a / b;
};
// 5. Optional Parameters
// 6. Default Parameters
// 7. Rest Parameters
// 9. Function Overloading
if (age) {
} else {
// Usage examples
console.log(add(5, 3)); // 8
console.log(subtract(10, 4)); // 6
console.log(multiply(4, 2)); // 8
console.log(divide(20, 5)); // 4
console.log(sum(1, 2, 3, 4)); // 10
Generics in TypeScript allow you to create reusable, flexible functions, classes, and interfaces that
can work with different types, without losing type safety.
// 1. Generic Function
return value;
// 2. Generic Arrays
return arr[0];
// 3. Generic Class
class Box<T> {
value: T;
constructor(value: T) {
this.value = value;
getValue(): T {
return this.value;
}
}
console.log(numberBox.getValue()); // 123
console.log(stringBox.getValue()); // "Hello"
// 4. Generic Interface
first: T;
second: U;
return item.length;
3. OOPS in typescript
// Abstraction: Abstract class
interface Employee {
name: string;
position: string;
showDetails(): void;
name: string;
constructor(name: string) {
this.name = name;
makeSound() {
console.log(`${this.name} barks.`);
position: string;
this.name = name;
this.position = position;
showDetails() {
console.log(`${this.name} is a ${this.position}`);
class Car {
accelerate(amount: number) {
if (amount > 0) {
this.speed += amount;
getSpeed(): number {
return this.speed;
console.log(car.getSpeed()); // Output: 50
function exampleVar() {
var a = 10;
if (true) {
var a = 20; // Re-declares and modifies the same variable in the function scope
exampleVar();
let a = 10;
console.log(a); // 10
if (true) {
console.log(a); // 20
console.log(a); // 10, because the 'a' in the block is different from the one outside
exampleLet();
const – block scope as that of let, can’t re-assign, object mutability(reference won’t be changed but
value gets changed)
function exampleConst() {
const a = 10;
console.log(a); // 10
console.log(obj.name); // "Doe"
exampleConst();
let a = 5;
console.log(a == b); // true, because '==' coerces the string "5" to a number before comparison
let a = 5;
console.log(a === b); // false, because a number is not strictly equal to a string
1. Array Functions
These are methods available on arrays in TypeScript, inherited from JavaScript's Array prototype.
arr.push(4); // [1, 2, 3, 4]
arr.pop(); // 3
arr.unshift(0); // [0, 1, 2, 3]
• shift(): Removes the first element from an array.
arr.shift(); // 1
• map():
Ex1 -
Ex2-
• filter():
Ex- 1
• reduce():
Applies a function to an accumulator and each element in the array (from left to right) to reduce it
to a single value.
1. Removing Elements
If you specify only startIndex and deleteCount, it removes elements from the array.
let arr = [10, 20, 30, 40, 50];
let removed = arr.splice(1, 2); // Removes 20 and 30
2. Inserting Elements
You can insert elements by providing item1, item2, ... after deleteCount.
let arr = [10, 20, 30];
arr.splice(1, 0, 15, 18); // Inserts 15, 18 at index 1
3. Replacing Elements
You can replace elements by providing new values for the removed elements.
let arr = [10, 20, 30, 40];
arr.splice(1, 2, 25, 35); // Removes 20, 30 and adds 25, 35
Syntax
array.slice(startIndex, endIndex);
1. Extracting a Subarray
let arr = [10, 20, 30, 40, 50];
let newArr = arr.slice(1, 4); // Extracts elements from index 1 to 3
2. String Functions
• toUpperCase():
• trim():
• substring():
• replace():
• split():
3. Number Functions
• toFixed():
• parseInt():
• parseFloat():
• isNaN():
4. Object Functions
• Object.keys():
let obj = { a: 1, b: 2 };
• Object.values():
let obj = { a: 1, b: 2 };
let values = Object.values(obj); // [1, 2]
• Object.entries():
Returns an array of a given object's own enumerable string-keyed property [key, value] pairs.
let obj = { a: 1, b: 2 };
7. Operators in typescript
// 1. Arithmetic Operators
let a = 10;
let b = 5;
a++; // Increment
console.log(a); // 11
b--; // Decrement
console.log(b); // 4
// 2. Assignment Operators
a = 10;
a += 5; // a = a + 5
console.log(a); // 15
a -= 3; // a = a - 3
console.log(a); // 12
a *= 2; // a = a * 2
console.log(a); // 24
// 3. Comparison Operators
console.log(a === b); // false (values and types are not equal)
// 4. Logical Operators
let x = true;
let y = false;
// 5. Ternary Operator
// 6. Type Operators
let c = "Hello";
let d = 10;
Ex -1
console.log(arr2); // [1, 2, 3]
Ex-2
let combined = [...arr1, ...arr2]; // Spread arr1 and arr2 into a new array
Ex-3
let newArr = [1, ...arr, 5]; // Add elements at the beginning and end
console.log(newArr); // [1, 2, 3, 4, 5]
console.log(combined); // [1, 2, 3, 4, 5, 6]
Ex-4
Ex-5 - object
console.log(mergedPerson);
return a + b + c;
console.log(sum(...numbers)); // 6
Ex 1 - with null
console.log(result); // "Guest"
Ex 2 – with undefined
console.log(result); // 25
8. Functions
// if-else
if (num > 0) {
console.log("Positive number");
} else {
console.log("Negative number");
// if-else if
console.log("Grade: A+");
console.log("Grade: A");
} else {
console.log("Grade: B");
// switch
const day = 2;
switch (day) {
case 1:
console.log("Monday");
break;
case 2:
console.log("Tuesday");
break;
default:
console.log("Invalid day");
// 2. Looping Statements
// for loop
// for...of loop
// for...in loop
// while loop
let i = 1;
while (i <= 5) {
// do-while loop
let j = 1;
do {
j++;
// break
// continue
console.log("Array after adding elements:", numbers); // [5, 10, 20, 30, 40, 50]
if (numbers.includes(itemToRemove)) {
console.log(`${itemToRemove} removed. Updated Array:`, numbers); // [5, 10, 20, 40, 50]
} else {
[1, "One"],
[2, "Two"],
[3, "Three"],
]);
map.set(5, "Five");
const keyToRemove = 3;
if (map.has(keyToRemove)) {
} else {
id: number;
name: string;
];
const idToRemove = 2;
} else {
]);
peopleMap.set(newPersonMap.id, newPersonMap);
const idToRemoveMap = 2;
if (peopleMap.has(idToRemoveMap)) {
peopleMap.delete(idToRemoveMap);
} else {