CodeToLive

Generics in TypeScript

Generics allow you to create reusable and type-safe components in TypeScript.

Generic Functions

Generic functions can work with any type.


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

let output = identity<string>("Hello");
      

Generic Classes

Generic classes can work with any type.


class Box<T> {
  value: T;

  constructor(value: T) {
    this.value = value;
  }

  getValue(): T {
    return this.value;
  }
}

let box = new Box<number>(10);
console.log(box.getValue());
      

Generic Interfaces

Interfaces can also be generic, allowing them to work with any type.


interface Pair<T, U> {
  first: T;
  second: U;
}

let pair: Pair<string, number> = { first: "Alice", second: 25 };
      

Generic Constraints

You can constrain generics to specific types.


interface Lengthwise {
  length: number;
}

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

logLength("Hello");
      

Default Generic Types

You can provide default types for generics.


function createArray<T = string>(length: number, value: T): T[] {
  return Array(length).fill(value);
}

let strings = createArray(3, "Hello");
      

Generic Utility Functions

Generics are often used in utility functions to make them more flexible.


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

let result = merge({ name: "Alice" }, { age: 25 });
      

Type Inference with Generics

TypeScript can often infer generic types based on the arguments passed.


let output = identity("Hello");  // TypeScript infers T as string
      

Built-in Generic Types

TypeScript provides built-in generic types like `Array` and `Promise`.


let numbers: Array<number> = [1, 2, 3];
let promise: Promise<string> = new Promise((resolve) => resolve("Done"));
      

Interactive Code Examples

Try running these examples in your TypeScript environment to see how they work!


// Interactive Example
function swap<T, U>(a: T, b: U): [U, T] {
  return [b, a];
}

let result = swap("Hello", 42);
console.log(result);
      

Practice Problems

Test your understanding with these practice problems:

  1. Write a generic function to reverse an array.
  2. Create a generic class `Stack` that supports `push` and `pop` operations.
  3. Write a generic function to find the maximum value in an array.
Back to Basics