Know when to use generics

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

Transcript

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.

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.

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.

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.

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.

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.

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.

More Tips