A Lazy Sequence

Leveraging Pick to simplify testing

Sometimes you have to write a function that takes a parameter that is some massive type that is outside of your control. That can be a nuisance to test. The amount of infrastructure needed to work around this will depend upon the size and scope of your project, but for the smaller projects TypeScript has a helpful tool: the Pick type.

Pick<T, K extends keyof T> is a mapped type. Pick produces a new type that is a subset of of T, with only the keys specified in K.

As an example, say you wanted test a function that consumes a Node http IncomingMessage. Producing a synthetic value of this type as written is going to require a lot of boilerplate. If you only need method and url, that’s a lot of overhead. Instead, if you specify your function as taking Pick<IncomingMessage, "method" | "url"> you can trivially mock up a series of plain JavaScript objects that fulfill that interface.

23 April 2018