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

You can DRY up your generics code MASSIVELY (and improve perf) by assigning local variables to default generic slots.

Here, we move some complex 'Extract' logic to a generic slot, meaning it only gets calculated once.

Discuss on Twitter

Transcript

You can do some really clever things with default parameters of generics, and they can really help tidy up really complicated-looking generic signatures. Here, we've got an object where what we want to do is we want to extract the values of the keys that start with A from this object.

This union, it's looking at the A, A2, A3, just here, and if I change this to foo, for example, it's extracting the values of those keys that start with A. It's a pretty messy type signature, because there's quite a bit of duplication here. Here, we're extracting the key of the objects, and we're saying we only want those keys that start with A in them. Then we return the part of the object that corresponds to that key.

Here, we're also doing it a second time, because we need to then map over the object in order to pull those values out. We can do something about this and reduce the duplication by saving it to a local variable. You might think, "Where on Earth would I save it here?"

Well, you can stick it inside the default parameters of a new private generic. If I call this extracted keys here, you can see that this is yelling at me, because it requires two type parameters. If I give it a default type parameter here, I can actually pass extract in there.

Now, we've got our keys all extracted already. What we can do is we can now get rid of these, and we can name them extracted keys instead. Now, there's an error going on here, because extracted keys, it says, it's not assignable to type string, number, or blah, blah, blah.

That's because it takes the value from the type of this generic here. If we add to it, and we say it extends a key of obj, then it starts working, because we say, "OK, this extracted keys extends the key of the object." Sorry, my cats are fighting.

Then we can just start using it here. This is now much easier to read, and our union still says the same.

More Tips