DEV Community

Cover image for TypeScript: Generic Types
donstefani
donstefani

Posted on

TypeScript: Generic Types

TypeScript is a statically typed superset of JavaScript that allows developers to write code with more safety and accuracy. Generic types in TypeScript make it possible to write reusable and flexible code by creating generic types that can be used with different data types.

You can use generic types to write functions, classes, and interfaces that can work with any data type. The syntax for creating a generic type in TypeScript is to use angle brackets <> to define the generic type parameter. For example:

function identity<T>(arg: T): T {
  return arg;
}
Enter fullscreen mode Exit fullscreen mode

Here, identity is a generic function that takes a type parameter T and returns a value of type T. The arg parameter is of type T, and the return value is also of type T. This means that the function can work with any data type.

We can call the identity function with different data types as follows:

let output1 = identity<string>("hello");
let output2 = identity<number>(10);
Enter fullscreen mode Exit fullscreen mode

In this example, we called the identity function with a string and a number as the type argument.

Another way of using generic types in TypeScript is with interfaces. We can create a generic interface that can work with any data type, as follows:

interface List<T> {
  data: T[];
  add(item: T): void;
  remove(item: T): void;
}
Enter fullscreen mode Exit fullscreen mode

In this example, List is a generic interface that has a data property of type T[] and two methods add and remove that take a parameter of type T. This means that we can create a List of any data type.

We can create a List of strings as follows:

let list = { data: ["apple", "banana"], add: function(item) { this.data.push(item); }, remove: function(item) { this.data.splice(this.data.indexOf(item), 1); } };
Enter fullscreen mode Exit fullscreen mode

In this example, we created a List of strings and added two items to it. We used anonymous object syntax to define the data, add, and remove properties.

In conclusion, generic types in TypeScript allow you to write flexible and reusable code that can work with any data type. It's possible to create generic functions, classes, and interfaces that can be used with different data types by defining a generic type parameter.

A good question is, "when should I use generic types, and are there any drawbacks to using them?".

More to come...

Top comments (0)