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:
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:
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.
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.