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.
More Tips
Type Predicates
1 min
TypeScript 5.1 Beta is OUT!
2 mins
How to Name your Types
4 mins
Don't use return types, unless...
4 mins
TypeScript 5.0 Beta Deep Dive
6 mins
Conform a Derived Type Without Losing Its Literal Values
1 min
Avoid unexpected behavior of React’s useState
1 min
Understand assignability in TypeScript
2 mins
Compare function overloads and generics
1 min
Use infer in combination with string literals to manipulate keys of objects
1 min
Access deeper parts of objects and arrays
1 min
Ensure that all call sites must be given value
1 min
Understand how TypeScript infers literal types
1 min
Get a TypeScript package ready for release to NPM in under 2 minutes
1 min
Use assertion functions inside classes
1 min
Assign local variables to default generic slots to dry up your code and improve performance
2 mins
Map over a union type
1 min
Make accessing objects safer by enabling 'noUncheckedIndexedAccess' in tsconfig
1 min
Use generics to dynamically specify the number, and type, of arguments to functions
1 min
Use 'declare global' to allow types to cross module boundaries
2 mins
Turn a module into a type
2 mins
Create autocomplete helper which allows for arbitrary values
2 mins
Use deep partials to help with mocking an entity
1 min
Throw detailed error messages for type checks
1 min
Create a 'key remover' function which can process any generic object
1 min
Use generics in React to make dynamic and flexible components
1 min
Create your own 'objectKeys' function using generics and the 'keyof' operator
1 min
Write your own 'PropsFrom' helper to extract props from any React component
1 min
Use 'extends' keyword to narrow the value of a generic
1 min
Use function overloads and generics to type a compose function
2 mins
Decode URL search params at the type level with ts-toolbelt
2 mins
Use 'in' operator to transform a union to another union
2 mins
Derive a union type from an object
2 mins