Mastering TypeScript Generics

March 25, 2024
10 min read
TypeScript

What are Generics?

Generics allow you to write flexible, reusable code while maintaining type safety. They let you create components that work with a variety of types rather than a single type.

Basic Generic Syntax

Simple Generic Function

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

// Usage
const result = identity<string>("hello");
const number = identity<number>(42);

Generic Constraints

You can constrain generic types to specific types:

interface Lengthwise {
  length: number;
}

function loggingIdentity<T extends Lengthwise>(arg: T): T {
  console.log(arg.length);
  return arg;
}

Advanced Patterns

Generic Interfaces

interface Container<T> {
  value: T;
  getValue(): T;
  setValue(value: T): void;
}

Conditional Types

type IsString<T> = T extends string ? true : false;

// Usage
type A = IsString<"hello">; // true
type B = IsString<42>; // false

Practical Examples

Array Utilities

function getFirstElement<T>(arr: T[]): T | undefined {
  return arr[0];
}

function mapArray<T, U>(arr: T[], fn: (item: T) => U): U[] {
  return arr.map(fn);
}

API Response Handling

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

async function fetchData<T>(url: string): Promise<ApiResponse<T>> {
  const response = await fetch(url);
  return response.json();
}

Best Practices

  1. Keep it simple - Don't over-generalize
  2. Document constraints - Make it clear what types are accepted
  3. Use meaningful names - T for type, K for key, V for value
  4. Test thoroughly - Generic code needs comprehensive testing

Conclusion

Generics are a powerful feature of TypeScript that enable you to write more flexible and maintainable code. Master them to take your TypeScript skills to the next level.

#typescript#generics#advanced#tutorial

Author

Kirtan Kalathiya

Full-stack developer passionate about creating exceptional web experiences. Sharing knowledge about web development, design, and technology.

💬 Discussion

Share your thoughts and insights about this article. Have questions? Let's discuss in the comments.