Know when to use generics

it's sometimes hard to work out if you should use a generic or if you shouldn't.

The first question I want you to ask yourself when you get to that point is are all the elements known when I make the function? Here in this getDisplayName function we take in an Animal and we return a displayName based on the animal's name.


interface Animal {
name: string
}
interface Human {
firstName: string
lastName: string
}
export const getDisplayName = (item: Animal): { displayName: string } => {
return {
displayName: item.name,
}
}

But what if we add a bit of dynamism here? Let's make it take in either an Animal or a Human


export const getDisplayName = (
item: Animal | Human
): { displayName: string } => {
return {
displayName: item.name,
}
}

But really, we still know all the elements and their types before we get into the function call. So what you'd probably do is this:


export const getDisplayName = (
item: Animal | Human
): { displayName: string } => {
if ("name" in item) {
return {
displayName: item.name,
}
}
}

And we'd do the same thing for the Human firstName and lastName and concatenate them together.

When you start needing a generic is when you truly don't know what type is going to be passed into the function or you have things inside the function that rely on knowing that type

Let's imagine that we do need to add a generic here in getDisplayName. We'll use TItem and extend Animal or Human.


export const getDisplayName = <TItem extends Animal | Human>(

Then in the return type we'll say TItem extends Human and returns a humanName. Otherwise, we'll return an animalName. And then inside the function body we'll return the animalName.


export const getDisplayName = <TItem extends Animal | Human>(
item: Animal | Human
): TItem extends Human ? { humanName: string } : { animal: string } => {
if ("name" in item) {
return {
animalName: item.name,
}
}
}

What that means is we get a different return type based on what we pass in. So when we pass in a name we get an animalName, and when we pass in a firtName and lastName we get a humanName back.

This is where you actually need a generic. Inside the function it has to decide what it returns. If we just did a union type, it wouldn't repsond to what gets passed in.

So this is a way to really hack TypeScript's inference and get that information so you can use it in your return types.

Transcript

0:00 It's sometimes hard to work out if you should use a generic or if you shouldn't. The first question I want you to ask yourself when you get to that point is are all of the elements known when I make the function? Here, in this get_display_name function, we take in an animal, and we return a display name based on the animal's name.

0:20 What if, woo, we add a bit of dynamism here. This looks like it's dynamic now, because it can either take in an animal, or it can take in a human, but really, we still know all the elements and all of their types before we get into the function call.

0:35 Here, what you probably do is, if name in item.name or if just item, in fact, then return display name, item.name, and you do the same thing for human, first name, last name, concatenate them together. When you start needing a generic is when you truly don't know what the type is going to be passed into the function, or you have things inside the function that rely on knowing that type.

1:03 Let's imagine that we do need to add a generic here, so we're going to say T item. T item is going to extend either animal or human. In here, what we're going to do is we're going to reference this here, and we're going to see T item extends human.

1:18 Then we're going to return a human name string. Other than that, we're going to return the animal name string. This is where things start getting complicated, because inside here, we now need to return the animal name, which is going to be item.name.

1:37 What that means, then, is we get a different return type based on what we pass in. Here, we're passing in an animal, and so we get animal name. Here, we're passing in a human name, and so we get a human name. This is where it truly starts.

1:51 You need to use a generic, basically, because inside the function, it has to decide what it returns. If we were to just return this as a union type, like either human name or animal name, then it wouldn't respond to what gets passed in. This is a way to really just hack TypeScript's inference and get that information so you can use it in your return types.

It can be hard to know when to reach for generics. Ask yourself:

Are there ZERO dynamic elements in your function? No generics needed.

If you have dynamic elements, do you know all their shapes up front? You might just need a union type.

Discuss on Twitter

More Tips

Play Type Predicates

Type Predicates

1 min

Play TypeScript 5.1 Beta is OUT!

TypeScript 5.1 Beta is OUT!

2 mins

Play How to Name your Types

How to Name your Types

4 mins

Play Don't use return types, unless...

Don't use return types, unless...

4 mins

Play TypeScript 5.0 Beta Deep Dive

TypeScript 5.0 Beta Deep Dive

6 mins

Play Conform a Derived Type Without Losing Its Literal Values

Conform a Derived Type Without Losing Its Literal Values

1 min

Play Avoid unexpected behavior of React’s useState

Avoid unexpected behavior of React’s useState

1 min

Play Understand assignability in TypeScript

Understand assignability in TypeScript

2 mins

Play Compare function overloads and generics

Compare function overloads and generics

1 min

Play Use infer in combination with string literals to manipulate keys of objects

Use infer in combination with string literals to manipulate keys of objects

1 min

Play Access deeper parts of objects and arrays

Access deeper parts of objects and arrays

1 min

Play Ensure that all call sites must be given value

Ensure that all call sites must be given value

1 min

Play Understand how TypeScript infers literal types

Understand how TypeScript infers literal types

1 min

Play Get a TypeScript package ready for release to NPM in under 2 minutes

Get a TypeScript package ready for release to NPM in under 2 minutes

1 min

Play Use assertion functions inside classes

Use assertion functions inside classes

1 min

Play Assign local variables to default generic slots to dry up your code and improve performance

Assign local variables to default generic slots to dry up your code and improve performance

2 mins

Play Map over a union type

Map over a union type

1 min

Play Make accessing objects safer by enabling 'noUncheckedIndexedAccess' in tsconfig

Make accessing objects safer by enabling 'noUncheckedIndexedAccess' in tsconfig

1 min

Play Use generics to dynamically specify the number, and type, of arguments to functions

Use generics to dynamically specify the number, and type, of arguments to functions

1 min

Play Use 'declare global' to allow types to cross module boundaries

Use 'declare global' to allow types to cross module boundaries

2 mins

Play Turn a module into a type

Turn a module into a type

2 mins

Play Create autocomplete helper which allows for arbitrary values

Create autocomplete helper which allows for arbitrary values

2 mins

Play Use deep partials to help with mocking an entity

Use deep partials to help with mocking an entity

1 min

Play Throw detailed error messages for type checks

Throw detailed error messages for type checks

1 min

Play Create a 'key remover' function which can process any generic object

Create a 'key remover' function which can process any generic object

1 min

Play Use generics in React to make dynamic and flexible components

Use generics in React to make dynamic and flexible components

1 min

Play Create your own 'objectKeys' function using generics and the 'keyof' operator

Create your own 'objectKeys' function using generics and the 'keyof' operator

1 min

Play Write your own 'PropsFrom' helper to extract props from any React component

Write your own 'PropsFrom' helper to extract props from any React component

1 min

Play Use 'extends' keyword to narrow the value of a generic

Use 'extends' keyword to narrow the value of a generic

1 min

Play Use function overloads and generics to type a compose function

Use function overloads and generics to type a compose function

2 mins

Play Decode URL search params at the type level with ts-toolbelt

Decode URL search params at the type level with ts-toolbelt

2 mins

Play Use 'in' operator to transform a union to another union

Use 'in' operator to transform a union to another union

2 mins

Play Derive a union type from an object

Derive a union type from an object

2 mins