Typescript Foundations / Generics

Generic interfaces

A Generic Interface allows you to define an interface that takes a type parameter, making it reusable with different types while keeping type safety.


✅ Basic Syntax

interface Box<T> {
  value: T;
}

const numberBox: Box<number> = { value: 123 };
const stringBox: Box<string> = { value: "hello" };

Here:

  • Box<T> is a generic interface.

  • T can be replaced with any type when used.


📦 Generic Interface with Arrays

interface Collection<T> {
  items: T[];
  add(item: T): void;
}

const stringCollection: Collection<string> = {
  items: ["apple", "banana"],
  add(item) {
    this.items.push(item);
  },
};

🔁 Multiple Type Parameters

interface Pair<K, V> {
  key: K;
  value: V;
}

const pair: Pair<string, number> = {
  key: "age",
  value: 25,
};

⛓️ Generic Interface with Constraints

You can restrict the types passed into the generic using extends.

interface HasLength {
  length: number;
}

interface Wrapper<T extends HasLength> {
  data: T;
}

const wrappedString: Wrapper<string> = { data: "hello" };
const wrappedArray: Wrapper<number[]> = { data: [1, 2, 3] };

// ❌ Error: number doesn’t have length
// const wrappedNumber: Wrapper<number> = { data: 123 };

⚙️ Default Type for Generics

interface ResponseData<T = any> {
  data: T;
  status: number;
}

const defaultResponse: ResponseData = {
  data: "some data",
  status: 200,
};

🧠 When to Use Generic Interfaces

Use them when:

  • You want to define reusable data structures (e.g., API response, form values, input props).

  • You need type safety but flexibility.

  • You want to abstract logic like in repositories, forms, or services.


🧪 Real-World Example: API Result

interface ApiResponse<T> {
  status: "success" | "error";
  data: T;
  message?: string;
}

interface User {
  id: number;
  name: string;
}

const userResponse: ApiResponse<User> = {
  status: "success",
  data: { id: 1, name: "Tisha" },
};


📌 Summary

Feature

Example

Basic Generic Interface

interface Box<T> { value: T }

With Arrays

items: T[]

Multiple Parameters

interface Pair<K, V>

Constraints

T extends HasLength

Default Types

interface Response<T = any>