-
Array
-
Objects
-
List Of Objects
Note: Ensure you have typescript globally
npm install -g typescript
How to run?
Example:
tsc array.ts
node array.js
An array is a data structure that stores a collection of elements (values), usually of the same type, in a single variable. Arrays allow you to store multiple values in an ordered list and provide easy access using an index.
In TypeScript, arrays can be declared to hold specific types, ensuring type safety. You can store a list of strings, numbers, or any other data types.
Here's how you can define an array in TypeScript:
-
Array of Numbers:
let numbers: number[] = [1, 2, 3, 4, 5];
-
Array of Strings:
let shoppingList: string[] = ["milk", "bread", "eggs"];
-
Array of Multiple Types (using
any
):let mixedArray: any[] = [1, "apple", true];
-
Using Generics (Another way to define arrays):
let fruits: Array<string> = ["apple", "banana", "orange"];
EXAMPLE: SHOPPINGLIST
let shoppingList: string[] = ["milk", "chocolate" , "shampoo"]; console.log("List: " + shoppingList);
shoppingList.push("Safeguard");
You can access elements in an array using their index. The index starts at 0
.
plaintext let firstItem = shoppingList[0]; let secondItem = shoppingList[1];
shoppingList[1] = "strawberry";
shoppingList.splice(2, 1); // Removes 1 item at index 2
This is how you use and manipulate arrays in TypeScript for basic operations like creating, reading, updating, and deleting elements.
An object in TypeScript is an instance that contains a set of key-value pairs. These pairs can hold various data types, including scalar values, functions, or even arrays of other objects. (GEEKSFORGEEKS)
shoppingObject.ts
export interface ShoppingObject{
id: number;
name: string;
price: number;
quantity: number;
}
main.ts
const shoppingObject: ShoppingObject = {
id: 1,
name: "test",
price: 20,
quantity: 2
};
console.log("List ");
console.log(shoppingObject);
main.ts
//Access value
console.log("=====ACCESSSSING=====");
const name: string = shoppingObject.name;
console.log("FETCH_ name: " + name);
main.ts
console.log("=====UPDATINGGG=====");
shoppingObject.name = "thirdy";
console.log("UPDATED_ now the object: " );
console.log(shoppingObject);
Defining interfaces or type, we will provide the property names and their types inside them and assign them as a explicit type the array. (https://www.geeksforgeeks.org/how-can-i-define-an-array-of-objects-in-typescript/#using-the-inbuilt-interfaces-and-type)
sample Array of Object
ShoppingListObj.ts
export interface ShoppingListObj{
id: number,
name: string,
price: number,
quantity: number
}
This function adds a new product to the products
array.
main.ts
const shoppingList: ShoppingListObj[] = [];
shoppingList.push({id: 1, name: "test", price: 100, quantity: 5});
shoppingList.push({id: 2, name: "second", price: 100, quantity: 5});
console.log("List ");
console.log(shoppingList);
-
Parameter: It accepts a parameter
shoppingList
of typeShoppingListObj
. This represents the new list you want to add. -
Operation: The shopping or cart is added to the
shoppingList
array using thepush()
method.
This function fetches a shoppingList by its id
.
const readMyCart = (id: number): ShoppingListObj | undefined => {
return shoppingList.find(p => p.id === id);
};
-
Parameter: The function accepts
productId
which is the ID of the product to search for. -
Operation: It uses
find()
to search through theproducts
array for the product with the matchingid
. -
Conditional Logging:
-
If the product is found, it logs "Product found" and returns the product.
-
If not found, it logs "Product not found" and returns
undefined
.
-
readProduct(1); // Tries to find the product with id = 1
This will search for the product with ID 1
. If it exists, the product will be logged and returned.
This function updates the fields of a product using its id
.
const updateMyCart = (id: number, updatedData: Partial<ShoppingListObj>) => {
const findIndex = shoppingList.findIndex(p => p.id === id);
if (findIndex > -1) {
shoppingList[findIndex] = { ...shoppingList[findIndex], ...updatedData };
console.log("UPDATED DATA: ");
console.log(updatedData);
console.log("UPDATED LIST: ");
console.log(shoppingList);
} else {
console.log("Product Not Found");
}
};
-
Parameters:
-
id
: The ID of the product to be updated. -
updatedData
: APartial<ShoppingListObj>
, meaning it allows you to pass only the fields you want to update, without needing to provide the whole product.
-
-
Operation:
-
The function uses
findIndex()
to locate the product in theproducts
array by itsid
. -
If the product is found, it updates the fields by using object spread (
...
) to merge the existing product data with the newupdatedData
.
-
updateMyCart(2, {name: "shampoo"});
This will update the product with ID 2
by setting its name
to shampoo
OUTPUT:
This function deletes a product by its id
.
const deleteItem = (id: number) => {
const findIndex = shoppingList.findIndex(p => p.id = id);
if (findIndex !== -1){
const deleteItem = shoppingList.splice(id, 1);
console.log("Deleted Item: " + deleteItem[0]);
console.log("UPDATED LIST: ");
console.log(shoppingList);
}
}
-
Parameter: It accepts
productId
, the ID of the product to be deleted. -
Operation:
-
It uses
findIndex()
to locate the product in theproducts
array. -
If the product is found, it is removed using
splice()
(which removes the product at the found index). -
The deleted product is then logged.
-
deleteItem(1); // Deletes the product with id = 1
This will remove the product with ID 1
from the shoppingList
array if it exists.
OUTPUT
-
Create: Adds a new product to the list.
-
Read: Retrieves a product by its ID.
-
Update: Modifies specific fields of a product.
-
Delete: Removes a product by its ID.
Each function uses basic array methods (push
, find
, findIndex
, splice
) to manipulate the products
array and logs the results for clarity.
GITHUB REPOSITORY:
https://github.com/thirdygayares/typescripts-data-structure.git