TypeScript 2.1 and the power of pick

Image for post
Image for post
This represents the very peak of my image editing skills

TypeScript 2.1 bought a lot of cool things to the table, but I’d like to talk about one thing in particular, a specific use of the “Pick” keyword. Generally speaking, interfaces are built up from one another, either defining a property of an interface as another interface, or making use of the “extends” keyword.

This works fine, and I still think it’s the de facto way for defining interfaces, but there are definitely alternatives with this situation:

No, that isn’t some crazy spread syntax, it’s me being lazy

We have our task interface, but now we need a partial task to work with before our invoice and employee assigning modules do their thing. There are quite a few ways to do this, some neater than others. Something like this is perfectly great:

You could also go with one of the other handy keywords: Partial. This will create a clone that mirrors the provided interface, but with all optional attributes:

This is a REALLY nice solution for situations where the data is going to have properties chunked on as it’s run through various transformation functions

There is probably another dozen ways to tack this. Or, you could upset me by adding ‘?’ to everything if you’re feeling lazy and enjoy watching the world burn.

Enter Pick

Pick gives us another nice little alternative to the above. 9/10 times this is not going to be the way you build types, but there is interesting ways you can use this that help better represent how we think of the data in a project.

What we could do here with pick, is break it down instead of build it up:

This approach has a massive benefit: We have an interface that defines a Task in its entirety without following around a chain of “extends”. This isn’t ground-breaking or world-shattering, but one of the biggest-yet-underrated advantages of TypeScript is how easy it is to examine data-flow through an application by looking at types in an interface file.

Being able to come into this project, and see that these are all the properties a task can have in this application is a very easy way to get your head around the data structures. It is the single source of truth for a task, from which all subsets are pulled, and I like what this does for my mental model of an application.

Team Codafication

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store