TypeScript 2.8 and a simple example of ReturnType

Curtis Tate Wilkinson
2 min readMay 2, 2018
ReturnType<T>

TypeScript 2.8 introduced the notion of conditional types, which is an immensely powerful concept that I recommend you go read in the release notes. Along with shipping these, they also release several predefined conditional types which I’ve already had some fun with (Exclude, Extract, NonNullable, InstanceType and ReturnType).

I wanted to quickly write up a quick real-world usage of ReturnType that I had recently, because I think it’s an easy example for explaining when it is super useful.

I was doing some front-end work and working with an awesome library called mobx-state-tree, which I am really enjoying at the moment. I wanted to have my store created and returned from a factory that I could provide my graphQL client to, here is a stripped down example:

A factory function that takes a client, and returns a store

One of the great things about mobx state tree (and mobx itself) is that they are implemented in TypeScript and the typings are great, but I wanted those wonderful typings in the form of an interface that I could import into distant corners of my application to represent my Store.

Now that we have access to ReturnType, that is made super easy:

Take note of the last line, it’s the only thing that has changed

To quickly break it down:

  1. We take the typeof StoreFactory , which gives us the type signature of the StoreFactory function
  2. We then pass that into the ReturnType type parameter, which takes a function type then gives back the type which will be returned when the function is invoked

Now I can change the definition of my store in my mobx state tree model, and that change will be reflected in the Store type that is being exported, which is exactly what I wanted. Hopefully that’s a nice and practical example of ReturnType in use.

You should check out the TS 2.8 release notes, as there was a lot of interesting stuff there, and if you find any cool uses for any of it I’d love to hear from you!

--

--