Step 10 – Generics in TypeScript

image 2

Play Store Application link – Java to TypeScript in 14 Steps – App on Google Play

Generics in TypeScript are like Java’s generics, allowing you to write code that can handle different types without knowing them upfront. They make your code more flexible and reusable by working with various data types in a type-safe manner.

Introduction to Generics

Generics let you create components that work with any type, but still enforce type safety. This is similar to Java’s generic types, which let you define classes and methods with type parameters.

Java Comparison:

In Java, you might use generics with classes like this:

public class Box<T> {
    private T value;

    public void setValue(T value) {
        this.value = value;
    }

    public T getValue() {
        return value;
    }
}

TypeScript Equivalent:

class Box<T> {
  private value: T;

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

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

Generic Functions

You can create functions that work with any data type by defining a generic type parameter.

Example:

function reverse<T>(arr: T[]): T[] {
  return arr.reverse();
}

const numbers = [1, 2, 3];
const reversedNumbers = reverse(numbers); // [3, 2, 1]

const strings = ['hello', 'world'];
const reversedStrings = reverse(strings); // ['dlrow', 'olleh']

Java Comparison:

In Java, a similar function would be a generic method:

public static <T> List<T> reverse(List<T> list) {
    Collections.reverse(list);
    return list;
}

Generic Interfaces

Generic interfaces let you define objects with flexible types. You can specify different types for different properties.

Example:

interface KeyValuePair<K, V> {
  key: K;
  value: V;
}

const kv1: KeyValuePair<number, string> = { key: 1, value: 'hello' };
const kv2: KeyValuePair<string, boolean> = { key: 'world', value: true };

Java Comparison:

In Java, it looks like this:

public class KeyValuePair<K, V> {
    private K key;
    private V value;

    public KeyValuePair(K key, V value) {
        this.key = key;
        this.value = value;
    }

    // Getters and setters
}

Generic Classes

Generic classes let you create classes that handle various types, just like generic classes in Java.

Example:

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

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

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

const stack = new Stack<number>();
stack.push(1);
stack.push(2);
stack.push(3);
console.log(stack.pop()); // 3
console.log(stack.pop()); // 2
console.log(stack.pop()); // 1

Java Comparison:

In Java, this would be:

public class Stack<T> {
    private List<T> items = new ArrayList<>();

    public void push(T item) {
        items.add(item);
    }

    public T pop() {
        if (items.isEmpty()) return null;
        return items.remove(items.size() - 1);
    }
}

Conclusion

Generics in TypeScript are a powerful tool for creating reusable and type-safe code. They allow you to work with different types in a flexible way, similar to Java’s generics. By using generics, you ensure that your code can handle various types while maintaining type safety, which helps prevent runtime errors and improves code quality.

Leave a Reply

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