Deep Partials In TypeScript

Deep Partials In TypeScript

Perfect for mocking complex types in unit or integration tests!

Posted on March 21, 2022

If you've been writing Jest tests with mock objects and so on, you know how much of a headache it is to mock objects. Of course in your testing code, you are often only concerned with testing specific properties of your object per test. TypeScript, however, doesn't really know or care about this fact, and will complain if you include . Luckily, there is a nice way to mock all these properties to keep TypeScript happy - no matter how deeply nested or complex your object is. To be able to fully mock any possible object that can exist in JavaScript, three parts are needed: type DeepPartial type: DeepPartialObject, and interface IDeepPartialArray:

interface IDeepPartialArray<T> extends Array<DeepPartial<T>> {}

type DeepPartialObject<T> = {
    [Key in keyof T]?: DeepPartial<T[Key]>

export type DeepPartial<T> = T extends Function 
? T 
: T extends Array<infer U>
? IDeepPartialArray<U> : T extends object
? DeepPartialObject<T>
: T | undefined;

All credit to Matt Pocock]( and his short video Tweet about this utility type and interface. (I recommend following him on Twitter and checking out his TypeScript content in general; it's fantastic!)


I hope this snippet is useful for you. We're definitely making use of it in our Jest tests at InClub

Cheers! 🍻


Next / Previous Post:

Find more posts by tag:

-~{/* */}~-