codez.guru

What are Generics?

Generics allow you to create flexible, reusable functions, classes, and interfaces while keeping strong type safety.

Instead of hardcoding a type, you make it a variable:

function identity<t>(value: T): T {
  return value;
}

Here, T is a type parameter, like a placeholder for the actual type.


Generic Functions

Define a function with a generic type:

function wrapInArray<t>(value: T): T[] {
  return [value];
}

const strArray = wrapInArray("hello"); // string[]
const numArray = wrapInArray(42);      // number[]

The type is inferred automatically based on input.


Generic Interfaces

You can make interfaces generic too:

interface ApiResponse<t> {
  data: T;
  success: boolean;
}

const userResponse: ApiResponse&lt;{ id: number }&gt; = {
  data: { id: 1 },
  success: true,
};

This works great for API types and abstract utilities.


Working with Type Parameters

You can reference generic types just like variables:

function getFirst<t>(arr: T[]): T {
  return arr[0];
}

Type parameters can also reference multiple types:

function pair<a b>(a: A, b: B): [A, B] {
  return [a, b];
}

Type Inference with Generics

Most of the time, TypeScript infers the generic for you:

const name = identity("Lior"); // T is inferred as string

But you can also explicitly pass it:

const explicit = identity<number>(123);

Common Use Cases

  • API response wrappers
  • Reusable utilities (e.g., filters, maps)
  • Component props in React
  • Form types and validators
  • Generic data models

Summary

  • Generics let you build flexible, reusable, type-safe code
  • Use <t> to define a placeholder type
  • Generics work in functions, interfaces, types, and classes
  • TypeScript often infers generic types — but you can specify them explicitly

Next up: Lesson 12 – Generic Constraints and Default Types, to add control and fallback behavior to your generics.