Learn Programming, Tech & Coding · Free Online Tools

IT Question Answer
Back to TypeScript

TypeScript Generics: Advanced Type Safety

TypeScript1,650 viewsBy Muhammad Fareed
typescriptgenericsadvancedtype-safety

TypeScript Generics: Advanced Type Safety

Learn TypeScript generics to create reusable, type-safe code components.

Basic Generic Function

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

const result = identity<string>('hello');

Generic Interfaces

interface Box<T> {
  value: T;
}

const numberBox: Box<number> = { value: 42 };
const stringBox: Box<string> = { value: 'hello' };

Generic Classes

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

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

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

Constraints

function getLength<T extends { length: number }>(arg: T): number {
  return arg.length;
}

Multiple Type Parameters

function merge<T, U>(obj1: T, obj2: U): T & U {
  return { ...obj1, ...obj2 };
}

Benefits

  • Type safety without losing flexibility
  • Reusable code components
  • Better IDE support and autocomplete
  • Catch errors at compile time