TypeScript Generics: Writing Flexible, Reusable Code

On this page

Generics let you write functions and classes that work with any type while maintaining type safety. They’re essential for reusable TypeScript code.

Basic Generic Function

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

const num = identity(42);       // number
const str = identity("hello");  // string

Generic Interfaces

TypeScript11 lines
interface ApiResponse<T> {
  data: T;
  status: number;
  message: string;
}

const userResponse: ApiResponse<User> = {
  data: { id: 1, name: "John" },
  status: 200,
  message: "Success"
};

Constraints

TypeScript5 lines
interface HasId { id: number; }

function findById<T extends HasId>(items: T[], id: number): T | undefined {
  return items.find(item => item.id === id);
}

References


Discover more from C4: Container, Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Written by

Nithin Mohan TK

Hello Namaste! 👋🏻 I'm an accomplished Enterprise Solution Architect & Engineering Leader with 20+ years of progressive experience architecting, building, and scaling transformative enterprise solutions. ⚜️ Solution Architect / AI & Cloud 📌 Galway, Ireland

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.