Harry Yates

I'm a web developer focused on TypeScript, React, and Three.js.

Generics in TypeScript

Fri, 8th Mar 2024

Generics in TypeScript are a tool for writing flexible and reusable code components that work with a variety of types.

They help maintain type safety without sacrificing the versatility of your functions or data structures.

When you call a generic function, you will most often provide the type argument, for example, <string> or <number>.

Post

Why Generics?

  • Type Safety: They ensure code remains type-safe, avoiding runtime errors related to type mismatches.
  • Reusability: Generics allow you to write code that operates across different types, enhancing code reusability.
  • Flexibility: Generics enable your code to work with any type, not just those known at development time.

SYNTAX

Post

To make a function generic, you must expect a type parameter, for example, <Type>. This is placed between the function name and its list of parameters.

  • The name of the type, let's go with Type (UpperCamelCase) it for now. but it's more common to see <T> used. Generics are probably the only place in programming where a single character is conventionally accepted instead of a descriptive name.
  • You then wrap it with angled brackets < and >. So, it becomes <Type>.
  • You place it between the name of the function and before its list of parameters.

The angled brackets must contain the name of the generic type. This is a placeholder representing the data type information inside that function. More on that in a second.

How It Works

Generics parameterise types in the same way functions parameterise values. This means you can create a function that accepts a type parameter and then use that type within the function body to ensure type safety.

Consider the need to retrieve the first element of any array. Without generics, your function might be limited to a specific type or utilise any, sacrificing type safety. Generics provide a solution:

Post

Here, <T> represents a placeholder for the type passed to the function when invoked. This allows the getFirst function to be used with arrays of any type whilst still being type-safe and flexible.

In Practice

When you use getFirst with an array of numbers, T is inferred as number. When used with an array of strings, T is inferred as string.

This adaptability makes generics a powerful feature in TypeScript for creating robust and maintainable code.