book cover front cover for API Development with Laravel by Akintoye Adegoke

πŸš€ It’s here!
After months of writing and testing real-world code examples, I’m excited to announce my new book β€” API Development with Laravel: A Quick Start Guide πŸŽ‰
This project-based book introduces you to Laravel, even if you’re completely new to it β€” and shows you how to build a real Payment Processor API step by step.

TypeScript's Generics In Short

TypeScript generics allow you to create reusable and flexible code by abstracting over types. It enables you to write code that can work with different types without explicitly specifying them.

Generics are defined using angle brackets (< >) and can be applied to functions, classes, and interfaces. They are represented by a placeholder type parameter, commonly denoted as T. This placeholder can be replaced with any type when the generic code is used.

Here's a simple example to illustrate TypeScript generics:

// A generic function that swaps the positions of two elements in an array
function swap<T>(arr: T[], i: number, j: number): void {
  const temp = arr[i];
  arr[i] = arr[j];
  arr[j] = temp;
}

// Usage
const numbers = [1, 2, 3, 4];
swap<number>(numbers, 1, 3);
console.log(numbers); // Output: [1, 4, 3, 2]

const strings = ['apple', 'banana', 'cherry'];
swap<string>(strings, 0, 2);
console.log(strings); // Output: ['cherry', 'banana', 'apple']

In this example, the swap function uses a generic type T to indicate that it can work with any type. When calling the function, you specify the actual type you want to use (e.g., number or string) within angle brackets.

By using generics, you can create reusable code that works with different types while maintaining type safety.

Comments