Harry Yates

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

Generic Constraints

Fri, 22nd Mar 2024

TypeScript has changed how we write JavaScript, offering a layer of type safety that catches errors before they happen.

One of its most powerful features is generics, which allows for the creation of flexible and reusable code.

Post

The Basics of Generics

Imagine you're a chef in a kitchen with a machine that can process any ingredient you throw into it to make a dish.

Generics work like that; they can handle any type you give them, making your code flexible and reusable.

But what if you want the machine only to accept certain ingredients to make a specific dish?

That's where generic constraints come into play.

Why Use Generic Constraints?

Continuing our kitchen analogy, suppose you're making a fruit salad. You want your machine only to process fruits, not any ingredient it encounters.

Generic constraints allow you to specify that only certain "types" (ingredients) are acceptable, preventing errors and ensuring your "dish" turns out as expected.

Introducing Constraints

Let's get technical. Say you have a function that should work only with objects with a price property.

Without constraints, TypeScript will complain if you try to access item.price, because it can't be sure every "item" has a "price".

Using a generic constraint, you can tell TypeScript, "Trust me, I'll only give you objects with a price", and TypeScript will let you proceed.

Here's how you do it:

Post

Now, TypeScript knows any item passed to displayItemPrice will have a price, making your code safe and error-free.

Going a Step Further: Default Types

TypeScript doesn't stop at constraints; it also allows you to set default types for generics.

If you don't specify a type, TypeScript will use a default, balancing flexibility and specificity.

How Does That Work?

Imagine if our machine was set to make a apple salad by default unless told otherwise.

Setting a default type does that. It tells TypeScript, "If I don't specify a type, assume it's this default."

Post

Now, if you don't specify a type for T, TypeScript will assume it's an UnlabeledItem, ensuring your code is flexible and type-safe.

Wrapping Up

Generic constraints in TypeScript are like having a kitchen that can make any dish but also specialises in certain cuisines when needed.

They ensure your code is flexible, reusable, and, above all, safe from unexpected errors.