T

Generics

TypeScript syntax guide

Creating reusable components that work with a variety of types

Generics

Creating reusable components that work with a variety of types

TypeScript generics (typescript)
        
          // Generic function
function identity<T>(value: T): T {
  return value;
}

// Generic class
class Stack<T> {
  private items: T[] = [];

  push(item: T): void {
    this.items.push(item);
  }

  pop(): T | undefined {
    return this.items.pop();
  }

  peek(): T | undefined {
    return this.items[this.items.length - 1];
  }
}

// Generic constraints
interface Lengthwise {
  length: number;
}

function logLength<T extends Lengthwise>(item: T): void {
  console.log(item.length);
}

// Usage
logLength("hello"); // OK
logLength([1, 2, 3]); // OK
// logLength(42); // Error: number has no length property

// Utility types
interface User {
  id: number;
  name: string;
  email: string;
  createdAt: Date;
}

// Partial - makes all properties optional
type PartialUser = Partial<User>;

// Pick - select specific properties
type UserCredentials = Pick<User, 'email'>;

// Omit - exclude specific properties
type UserWithoutId = Omit<User, 'id'>;

// Record - create object type with specific key/value types
type UserRoles = Record<string, 'admin' | 'user' | 'moderator'>;

// Mapped types
type ReadonlyUser = {
  readonly [K in keyof User]: User[K];
};

// Conditional types
type IsString<T> = T extends string ? 'yes' : 'no';

type A = IsString<string>;  // 'yes'
type B = IsString<number>;  // 'no'

// Template literal types
type EventName = 'click' | 'hover' | 'focus';
type EventHandler = `on${Capitalize<EventName>}`;

// Utility type examples
const partialUser: PartialUser = { name: "John" };
const credentials: UserCredentials = { email: "john@example.com" };
const roles: UserRoles = {
  "john": "admin",
  "jane": "user"
};
        
      

Explanation

Generics allow you to write flexible, reusable code that works with any data type while maintaining type safety. They enable components to work over a variety of types rather than a single one.

Common Use Cases

  • Creating generic data structures (e.g., arrays, lists)
  • Building reusable functions that operate on different types
  • Developing type-safe libraries

Related TypeScript Syntax

Master Generics in TypeScript

Understanding generics is fundamental to writing clean and efficient TypeScript code. This comprehensive guide provides you with practical examples and detailed explanations to help you master this important concept.

Whether you're a beginner learning the basics or an experienced developer looking to refresh your knowledge, our examples cover real-world scenarios and best practices for using generics effectively in your TypeScript projects.

Key Takeaways

  • Creating generic data structures (e.g., arrays, lists)
  • Building reusable functions that operate on different types
  • Developing type-safe libraries