DEV Community

Cover image for Generic Types in TypeScript
Alvison Hunter Arnuero | Front-End Web Developer
Alvison Hunter Arnuero | Front-End Web Developer

Posted on • Updated on

Generic Types in TypeScript

Hey there, fellow TypeScript enthusiast! Have you ever come across the term "Generic Types" in TypeScript? If you're diving into the world of TypeScript, you might have encountered it before. Generic Types are like the Swiss Army knife of TypeScript – they empower you to write code that's not only flexible but also reusable.

In this brief introduction, we'll explore what Generic Types are and how they can enhance your TypeScript code. Whether you're a seasoned TypeScript developer or just starting out, getting a grip on Generic Types is key to mastering TypeScript. So, let's dive in and unravel the magic of Generic Types together!

What is a Generic Type?

In TypeScript, a generic type is like a master key, designed to unlock a variety of data types with a single, reusable code pattern. Imagine being able to write one function or type that can adapt to different kinds of data effortlessly. That’s the magic of generics—they let you create flexible, reusable code without the need to repeat the same logic for each data type.

Defining a generic type is a breeze. You use the angle bracket syntax <> and a type parameter, which acts as a placeholder for the actual type that will be specified later. Think of it as a fill-in-the-blank for types, allowing your code to be both versatile and type-safe.

For example, the following code defines a generic type called "ArrayWrapper" that takes a type parameter T, which can be any type:

type ArrayWrapper<T> = {
  array: T[],
  length: number
}
Enter fullscreen mode Exit fullscreen mode

In this example, "ArrayWrapper" is a generic type that wraps an array of a certain type and also provides the length of the array. The actual type of the array is specified by the type parameter T.

To use a generic type, you need to provide the actual type for the type parameter. For example, you can create an "ArrayWrapper" for an array of numbers as follows:

type ArrayWrapper<T> = {
  array: T[],
  length: number
}

const createArrayWrapper = <T>(array: T[]): ArrayWrapper<T> => {
  return {
    array,
    length: array.length
  };
}

const numberArrayWrapper: ArrayWrapper<number> = createArrayWrapper([1, 2, 3, 4]);

console.log(numberArrayWrapper);
Enter fullscreen mode Exit fullscreen mode

Here, the type parameter T is replaced with the number type, and "numberArrayWrapper" is a variable of type "ArrayWrapper" that wraps an array of numbers and provide you with the length of that Array you passed as a property value of this numberArrayWrapper.

Second Example

A generic type is like a chameleon in your code, effortlessly adapting to different environments. By parameterizing a type with other types, you unlock the magic of reusability and flexibility. This means you can write code once and have it work seamlessly with various data types, without the hassle of crafting separate implementations for each one. It's a game-changer for cleaner, more efficient programming!

Here's another example of defining a generic type:

const identity = <T>(arg: T): T => arg;
Enter fullscreen mode Exit fullscreen mode

In this example, the identity function takes a parameter arg of type T and returns a value of the same type T. The syntax before the function name indicates that T is a generic type parameter. This could be any letter or name, but as an standard we use the T as per TypeScript's Documentation.

We can call the identity function with different types:

const identity = <T>(arg: T): T => arg;

const fullName = identity<string>("Alvison Hunter");
// fullName's string type.
console.log(typeof fullName); 

const currentAge = identity<number>(48);
// currentAge's the number's type.
console.log(typeof currentAge); 

const isAvailable = identity<boolean>(true);
// isAvailable's 'boolean' type.
console.log(typeof isAvailable); 
Enter fullscreen mode Exit fullscreen mode

In the first call, T is inferred to be string, and the return type of identity is string. In the second call, T is inferred to be number, and the return type of identity is number.

Wrap-up

In TypeScript, generic types are a powerful tool for crafting adaptable and safe code. Whether you're working with functions, classes, or interfaces, generics empower you to write code that gracefully handles multiple data types. By leveraging generics, you create code that's not only more flexible and reusable but also makes your programming tasks smoother and more efficient.

Thanks for reading this article, I hope you enjoyed it as much as I did writing it. Until next time, dear readers!

❤️ Enjoyed the article? Your feedback fuels more content.
💬 Share your thoughts in a comment.
🔖 No time to read now? Well, Bookmark for later.
🔗 If it helped, pass it on, dude!

Top comments (0)