Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon TypeScript Generics Example code


TypeScript Generics Example code


Here is an example of using generics in TypeScript:

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

// Using the generic function
let output = identity<string>("hello");
console.log(output); // Output: hello

// Generic class
class Box<T> {
  private value: T;

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

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

// Using the generic class
let box = new Box<number>(42);
console.log(box.getValue()); // Output: 42

// Generic interface
interface Transformer<T, U> {
  (input: T): U;
}

function uppercase(input: string): string {
  return input.toUpperCase();
}

let transform: Transformer<string, string> = uppercase;
console.log(transform("hello")); // Output: HELLO

// Constrained generics
interface HasLength {
  length: number;
}

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

console.log(getLength("hello")); // Output: 5
console.log(getLength([1, 2, 3])); // Output: 3
// console.log(getLength(42)); // Error: Argument of type 'number' is not assignable to parameter of type 'HasLength'

In this example, we demonstrate the following uses of generics in TypeScript:

1. Generic function: The `identity` function takes a type parameter `T` and returns a value of the same type.
2. Generic class: The `Box` class has a type parameter `T` that is used for the type of the `value` property.
3. Generic interface: The `Transformer` interface has two type parameters, `T` and `U`, representing the input and output types of the function.
4. Constrained generics: The `getLength` function takes a type parameter `T` that extends the `HasLength` interface, ensuring that the argument has a `length` property.

The key benefits of using generics in TypeScript are:

- Type safety: Generics help maintain type safety by ensuring that the types used throughout your code are consistent and correct.
- Reusability: Generics allow you to write code that can work with a variety of data types, making your components more reusable.
- Flexibility: Generics provide a way to abstract over types, allowing you to write more flexible and adaptable code.

By using generics, you can create functions, classes, and interfaces that are type-safe and can work with a variety of data types, making your TypeScript code more robust and maintainable.

Citations:
[1] https://www.typescriptlang.org/docs/handbook/2/generics.html
[2] https://www.freecodecamp.org/news/typescript-generics-use-case-example/
[3] https://www.w3schools.com/typescript/typescript_basic_generics.php
[4] https://www.freecodecamp.org/news/how-typescript-generics-work/
[5] https://www.digitalocean.com/community/tutorials/how-to-use-generics-in-typescript