Generics in TypeScript with example

TypeScript Generics

TypeScript Generics is a way to create reusable components. It creates the flexibility of working with a variety of data types rather than a single data type.

To specify the generic type, we need to write <T> in TypeScript.

The concepts in TypeScript Generics are almost similar to C# and Java generics. Generic classes, generic functions, generic methods, and generic interfaces can be created in TypeScript.

TypeScript Generics example:

  function getGenericItem<T>(list: T[]): T[] {
    // @ts-ignore
    return [].concat(list);
  }

  const numberList = getGenericItem<number>([100, 200, 300]);
  const strList = getGenericItem<string>(['Joe Smith', 'Jenny Smith']);
  console.log(numberList);
  console.log(strList);