Skip to main content

Data Structure in Typescript

Updated 5 min readMarkdown
Data Structure in Typescript

Data Structures in TypeScript

In TypeScript, data structures are used to organize and store data. TypeScript’s strong typing system helps make sure the data is correct, which prevents common errors. Let's look at some common data structures, how they work, and their real-life uses, with simple code examples.

1. Arrays

  • What it is: An array is a list of items stored in a specific order.

  • Features:

    • Items are stored in order and can be accessed by their position (called an index).

    • All items must be the same type (e.g., all numbers, all strings).

  • When to use: When you need a list of related items like numbers or names.

  • Time Complexity:

    • Accessing an item: O(1) (quick).

    • Adding or removing from the end: O(1).

    • Adding or removing from the beginning or middle: O(n) (slower as more items are involved).

  • Code Example:

      let numbers: number[] = [1, 2, 3, 4];
      numbers.push(5);  // Adds 5 at the end
      numbers.pop();    // Removes the last item (5)
      console.log(numbers[0]);  // Shows the first item (1)
    

2 . Tuples

  • What it is: A tuple is like an array, but it can hold different types of items at fixed positions.

  • Features:

    • Fixed size, and each position can store a different type of item.
  • When to use: When you need to store related items of different types, like a name and age.

  • Code Example:

    •   let person: [string, number] = ["Alice", 25];
        console.log(person[0]);  // "Alice"
        console.log(person[1]);  // 25
      

3. Dynamic Arrays (ArrayList)

  • What it is: A dynamic array can grow or shrink as you add or remove items.

  • Features:

    • Automatically adjusts its size when you add more items.
  • When to use: When you don’t know in advance how many items you will need to store.

  • Code Example:

      let dynamicArray: number[] = [];
      dynamicArray.push(1);  // Adds 1
      dynamicArray.push(2);  // Adds 2
      console.log(dynamicArray);  // [1, 2]
    

4. Stack

  • What it is: A stack is like a pile of plates—you can only add or remove from the top. It follows the "Last In, First Out" rule (LIFO).

  • Features:

    • Add items to the top (push), remove from the top (pop), and look at the top item (peek).
  • When to use: When you need to reverse things or undo recent actions.

  • Code Example:

      class Stack<T> {
        private items: T[] = [];
        push(item: T) { this.items.push(item); }
        pop() { return this.items.pop(); }
      }
    
      let stack = new Stack<number>();
      stack.push(10);
      stack.push(20);
      console.log(stack.pop());  // 20
    

5. Queue

  • What it is: A queue works like a line at a store—the first person in line is the first to be served. It follows the "First In, First Out" rule (FIFO).

  • Features:

    • Add items to the back (enqueue) and remove items from the front (dequeue).
  • When to use: When tasks need to be done in the order they arrive, like in customer service.

  • Code Example:

      class Queue<T> {
        private items: T[] = [];
        enqueue(item: T) { this.items.push(item); }
        dequeue() { return this.items.shift(); }
      }
    
      let queue = new Queue<number>();
      queue.enqueue(1);
      queue.enqueue(2);
      console.log(queue.dequeue());  // 1
    

6. Linked List

  • What it is: A linked list is a series of items (nodes) connected like a chain. Each node holds some data and points to the next one.

  • Features:

    • Can grow or shrink easily.

    • Each node contains data and a link to the next node.

  • When to use: When you need to frequently add or remove items from anywhere in the list.

  • Code Example:

  •   class Node<T> {
        data: T;
        next: Node<T> | null = null;
        constructor(data: T) { this.data = data; }
      }
    
      class LinkedList<T> {
        head: Node<T> | null = null;
        append(data: T) {
          let newNode = new Node(data);
          if (!this.head) {
            this.head = newNode;
          } else {
            let current = this.head;
            while (current.next) current = current.next;
            current.next = newNode;
          }
        }
      }
    

7. HashMap (or Map/Object)

  • What it is: A HashMap (or Map) stores key-value pairs, where each key is unique and helps you quickly find its value.

  • Features:

    • Fast lookups based on a key.
  • When to use: When you need to quickly find something using a unique identifier (like a dictionary).

  • Code Example:

      let map = new Map<string, number>();
      map.set("Alice", 25);
      console.log(map.get("Alice"));  // 25
    

8. Set

  • What it is: A Set is a collection of unique items, meaning no duplicates.

  • Features:

    • Automatically prevents duplicate values.
  • When to use: When you need to store unique items, like user IDs or names.

  • Code Example:

      let set = new Set<number>();
      set.add(1);
      set.add(2);
      set.add(2);  // Won’t add 2 again
      console.log(set.has(1));  // true
    

9. Tree (Binary Search Tree)

  • What it is: A binary search tree (BST) is like an upside-down family tree. Each node has two children, one smaller than itself (left) and one larger (right).

  • Features:

    • Helps you organize data for quick searches.
  • When to use: When you need to quickly search, insert, or delete items, like in a search engine or database.

  • Code Example:

      class TreeNode {
        data: number;
        left: TreeNode | null = null;
        right: TreeNode | null = null;
        constructor(data: number) { this.data = data; }
      }
    
      class BinarySearchTree {
        root: TreeNode | null = null;
    
        insert(data: number) {
          const newNode = new TreeNode(data);
          if (!this.root) {
            this.root = newNode;
          } else {
            this.insertNode(this.root, newNode);
          }
        }
    
        private insertNode(node: TreeNode, newNode: TreeNode) {
          if (newNode.data < node.data) {
            if (!node.left) node.left = newNode;
            else this.insertNode(node.left, newNode);
          } else {
            if (!node.right) node.right = newNode;
            else this.insertNode(node.right, newNode);
          }
        }
      }
    

These are the most common data structures in TypeScript. Each has its own strengths and uses. TypeScript’s strong typing helps ensure you work with data in the right way, reducing mistakes in your code.

no references -5