Use deep partials to help with mocking an entity

Deep partials are SUPER useful and not natively supported by TypeScript. Here, I use one to help with mocking an entity in a (imaginary) test file.

Discuss on Twitter

Transcript

DeepPartials are incredibly useful for very, very narrow use cases. For instance, if you're in a test file, let's say, you're writing a unit test or something, and you want to make a seed for something, you have an entity that you want to mock, basically, let's say, it's a post here, you don't really want to have to go into, say, comments, value, this, for instance, and have to mock out all of everything every single time.

Usually, what you want to do is just provide a little bit of it enough to make the test run, essentially. What you can do there is you can use a DeepPartial for this. Now, a DeepPartial, if you were to just wrap this in a partial, for instance, which is something that TypeScript gives you, then you would, for instance, have meta.

Let's say you wouldn't need to provide meta. Let's say that you do provide meta, then you still have to provide description and a name because the partial is only one level deep. It doesn't go deeper. A DeepPartial, as we've got there, it actually goes and makes everything inside it partial, too. Even in comments here, we don't have to provide this value here.

Again, this is very, very useful for very narrow use cases. Let's break down how this works. We have DeepPartial where we have a thing, essentially. And if that thing extends a function, then we just return the thing because there's nothing to make it partial there. If it extends an array, and we infer the inferred array member, then we use DeepPartial array, which, basically, just calls DeepPartial on the thing inside it.

Otherwise, if it's an object, then for each key of the thing, then we, first of all, make sure it's not required there. That's crucial. Then we call DeepPartial on that thing again. You can see how it just gets recursively partialed down until everything is there.

More Tips