Sobes.tech
Middle

What are generics?

sobes.tech AI

Answer from AI

Generics in TypeScript allow creating components (functions, classes, interfaces) that can work with various data types while maintaining type safety. They enable writing more flexible and reusable code without losing the benefits of static typing. The simplest example is using generics in functions to return the same type as was passed as an argument.

// Function that accepts an argument of any type and returns it
function identity<T>(arg: T): T {
    return arg;
}

// Using a generic with a specific type - string
let outputString = identity<string>("string"); // outputString will be of type string

// Using a generic with automatic type inference - number
let outputNumber = identity(123); // outputNumber will be of type number

Generics can also be used in classes:

// Class working with elements of any type
class GenericBox<T> {
    value: T;
    constructor(initialValue: T) {
        this.value = initialValue;
    }
}

// Creating an instance of GenericBox with type string
let stringBox = new GenericBox<string>("hello");
// Creating an instance of GenericBox with type boolean
let booleanBox = new GenericBox(true); // TypeScript will infer the type

And in interfaces:

// Interface with a generic
interface KeyValuePair<K, V> {
    key: K;
    value: V;
}

// Using the interface with specific types
let stringNumberPair: KeyValuePair<string, number> = { key: "age", value: 30 };

Advantages of using generics:

  • Code reuse: The same structure can be used with different data types.
  • Type safety: The compiler checks types during compilation, preventing potential errors.
  • Readability and maintainability: The code becomes more understandable as it clearly shows which types the component works with.

Generics are often used in libraries and frameworks such as React (for typing component props), Redux (for typing the store), and when working with data collections.