Learn about inferring with reverse mapped types to create great inferences for arguments that aggregate different items of the same shape. The technique can help you to introduce type-level relationships within objects and tuples. The talk will start with the introduction to the technique and will go through a couple of real-world-like examples of how this can be used to improve library types.
Infer multiple things at once with reverse mapped types
AI Generated Video Summary
Mateusz Kruzynski introduces reverse map types and demonstrates their use in transforming object types. He discusses how reverse map types can be used for inference and to provide contextual types for parameter types. He also shows how reverse map types can be used to extend an entity and bind event listeners. In the context of state machines, he explains how reverse map types can be utilized to strongly type the initial property and create hierarchical state machines. However, there are limitations to be aware of, such as inferring a single thing per object property or tuple element.
1. Introduction to Reverse Map Types
My name is Mateusz Kruzynski. I work at Stately and maintain popular open source projects like Emotion, Redux Saga, ChangeSets, XState, and contribute to TypeScript. Today, I'll talk about inferring multiple things at once with reverse map types. Map types are type-level functions that transform object types. They can transform property values and property keys. Let's see an example with object type transformation using the identity function.
My name is Mateusz Kruzynski. I work at Stately, where we work on state machines and all the things related to that. I also maintain a couple of popular open source projects, like Emotion, Redux Saga, ChangeSets, XState, obviously, and I also contribute to TypeScript from time to time. And I'd like to tell you today more about inferring multiple things at once with reverse map types.
So, let's start with a short recap on what map types really are. So, they are sort of like a type level function and they accept a union of keys, they output an object type, and they are very useful for object type transformation. They are commonly used for transforming object property values but since TypeScript 4.1 it's also possible to transform object property keys.
So, in a sense we just have our x, our n input, and we transform it into our y with whatever transformation that TypeScript syntax just allows us to. So, let's take a look at a short example. We define our input is an object type with two properties, foo and bar, and they both have different types. So, we define also our type of the function. This one is just identity. And we can see how the syntax looks like for it. We put in square brackets our k. That is like our i in a for loop. So, we can use use that to look up that property in our type parameter t and use that value somehow. In here, we just grab the same thing and return it back. Now, we can try to call it a type level, and the point is that we should be we should actually get the same thing just back. So, we can inspect that, and yes, this is the very same type.
2. Reverse Map Types and Inference
Let's take a look at something more useful in practice. We define a type-level function called promiseify, which wraps a key of t with a function that returns a promise of that type. Reverse map types deal with the transformation from X to Y, where we know the transformation and the output Y, and we try to figure out the input X. This is useful for inference. We can define objects and provide contextual types for parameter types using type-level functions.
Let's perhaps take a look at something slightly more useful in practice. We can define another type level function. This one is promiseify, and we do the very similar thing. We iterate over key of t with our k, and just wrap the current k of t with a function that returns a promise of that type. So we reuse our earlier object type and treat that as some kind of RPC object here. Now we can try to use it at runtime, we can chain off a bar method of it, and then we can see that we actually can use it, so it's a promise, and in the callback we receive our value. And upon inspection, we can see that this bar property is indeed a function that returns a promise of number and val is being successfully resolved to a number type.
So what are reverse map types and how they relate to what we just discussed? So with reverse map types, the situation is just slightly different because we still deal with a transformation from X to Y. But this time it's a little bit reversed because what we know is the transformation itself and the end result, our output Y. And what we are trying to figure out is what we got as an input to satisfy this transformation into Y. So we try to figure out what's our input, what's our X here. And what is this actually useful for? It's useful for inference. Kensi.s asked on Twitter how one can do this sort of thing and this actually inspired this talk.
So let's take a look at this example. So the question here is how he can try to define an object and provide some contextual type to it for like parameter types add those different keys to resolve to those keys themselves. So in the method A, how we can resolve parameter name to A and how we can do the same for B and how we can resolve name there to be. So this can't really be done with satisfies because satisfies doesn't participate in inference and we can't really like create a candidate for it here but we can do that with with functions so let's take a look how we can do that here. So let's first define a type level function satisfy name to resemble what we had on the previous slide and this is this very operation we iterate over key of T with K and just produce a function that gets K as its name parameter and it can freely return return just anything because it's the return type is typed as void. Now to actually utilize it we need to introduce a function, we call it satisfy object name and we reuse that type level function that we just declared previously. And the tricky part is that now in here that object literal that we passed the satisfy object name function is kind of our output and we need like the TypeScript inference engine has to reverse what the input for this could be. So we can see that it can actually do that like we can solve Kant's puzzle and we can like resolve those keys here for those parameter types and we can look it up on the satisfyObjectName function that it indeed successfully inferred some input object that if we'd provided between like between angle brackets used as an explicit type parameter we could go from this object to this output that we have seen as an argument pass to the satisfyObjectName function. Let's continue with a more advanced example of the provideValue function and again we declare a type level function here and this time we put k of t at the val property of this whole template of this mapped type and we also introduce a new property which is a cb that stands for callback and we use that same k of t here as a like in a function so we should be able to resolve to whatever has been used as the val property. We should be able to use that as the parameter type for this function and now we can see that it's indeed able to figure out that it it should use that specific type of value property for both a and b the top level keys of this of this input object and we can see that in here it was indeed able to like zip this whole object into a simpler form to answer again the question of what the input could be to satisfy this whole mapping operation and for this output to be produced here i've highlighted here those spots here that were used to create this input object and if we take a look at our template in the mapped type we'd see that those spots relate exactly to our template and that TypeScript was able to reverse-engineer in a way that input type. Let's continue with another example. This time we declare some, let's say, database entity, user that has three properties, name, last, and age. Again, we define our template for our map type and in here we specify some requirements for the whole transformation and the needs property. Notice that this can be like just anything here, we don't really care what that will be, we'll use it in a specific way but at this point it's unbound and it could actually resolve to just anything. But whatever we will put at this needs property will be used in the compute property and this time we pick from the user object, key of this k of t which resolves to our needs property at this very specific like position and we intersect that with key of user. This is a neat trick to like filter those properties because whatever we put in the needs property should those should be properties of the user user object. So by intersecting those requirements at the needs position with the actual keys of the user we just create a common set of those two things so it's like filtering at the map at the type level.
3. Extending User Entity and Reverse Map Types
We extend our user entity with the family name property and compute its value. The result is a single unbinding function that can be passed back to React for cleanup. The reverse map type is constrained to possible event types of a specific HTML element. We use bindings and iterate over an array of strings to retrieve possible event types. Each listener deals with its own specific event type, providing a good developer experience. The original signature of Bundle is downsized to a single signature, improving readability. For the full implementation, check the bind event listener package.
And in here we extend our like user entity with the family name extra property. We specify its requirements. We see that we specify that we need the last property and we try to compute its value, the value of this family name thing. And in here we use the property last of this user object and this sound and value. And that whole thing returns a single unbinding function or it could return such that could be in turn just passed back to React and it could invoke that when it's cleaning up the effect that the setup effect. It's pretty neat because it just removes some boilerplate for us at the expense of using this small utility.
So let's take a look how it's defined. We have here its declaration, we bind the type parameter that resolves to some HTML element and now we can use its keys to compute to like constrain our reverse map type to only possible event types of that specific HTML element. So we won't be able to use event types that are not related to this one and then we just use those two bound type parameters here. We pass t to the first argument that is our target and we spread a list of bindings from those types for the listeners parameter position. That little spread just helps TypeScript to to infer to actually infer a tuple here because otherwise it could infer an array so it's a little hint for TypeScript to do what we want it to.
What is a binding here? So we can see here that we have our t that has a read-only we have bindings here and that accepts our t type parameter that has a constraint of read-only array of strings. So to iterate over an array or a tuple we use the very same syntax as we are using for mapping over object properties. So we do exactly that here, we use k of t as the type property here and use that k of t within the listener parameter here, and we use that type to somehow retrieve possible event types with the help of an extra type that's a bit like outside of this presentation, so let's assume that it just exists. We also have this possible event type that grabs a list of keys of our target and tries to infer possible event types, but remember that from from here we'll be returning just some strings like click, blare, input, etc. But the getEvent helper that I didn't show was supposed to map those strings to actual event types, and we can see that this example is able to resolve at each specific position specific event types. So for the blare event, for the blare type this is a focus event, whereas for the click type this is a mouse event. This is very nice because we were able to just narrow it down as much as possible so each listener can deal with its own specific event type instead of having to deal with every other type that could appear here within this whole tuple. And what's nice about it is also that auto-completes work pretty nice here so we can, what's cool about it is that auto-completes work here and so we can even provide a good developer experience for those things here. And thanks to the possible event type helper there that was computing the allowed event types, all of them appear here. This is pretty nice because the original signature of Bundle was using like a ton of overloads, I think like up to ten perhaps. But with those reverse map types applied here, we can just downsize all of it to just a single signature, which is a big readability improvement. For the full implementation of this helper, you can look into this repository, into this bind event listener package.
4. Utilizing Reverse Map Types in State Machines
Let's talk about utilizing reverse map types in the context of state machines. We can strongly type the initial property and constrain it to only the states that exist in the configuration. Transitions are also bound to the states in the configuration. Recursion can be used to create hierarchical state machines, allowing for nested states and transitions. This delivers a great developer experience, as the accepted types are bound correctly at each level of the state machine. However, there are some limitations to be aware of, such as inferring a single thing per object property or tuple element.
So let's talk now about what I love. So state machines. Let's take a look how we can utilize reverse map types in this context. This create machine function that accepts some initial state, a list of those states like the first state, second state and the third one. And each of those also have a defined transitions for them. They can accept events to change the current state into another state within this whole configuration object here. And that create machine function can be defined like this one.
What's neat here is that we have a mapping of all of those things, of all of those properties. We define our own record that will point to different states, but we also can refer to this whole reverse map type, like outside of it. So we can strongly type the initial property that is being used outside of it and we can verify that it works. Here autocompletes work great and we successfully were able to constrain this property to only those states that exist in this very configuration. And in a similar manner, transitions here are also bound to only those states that appear in this configuration and you can select them from the list and all of that jazz.
Let's talk about recursion because it would be really cool to do those things recursively and it turns out that we can actually do that also using an expanded version of the createMachine function. So in here, this is very similar to the previous one. It just defines a hierarchical state machine that means that within states we can have more states and such like a compound state can point to its children with its own initial property. We define a signature for createMachine here. As the configure we use a helper state type and that is very similar to the previous one with a very small just change. In here we are using state recursively. So as long as K of T appears naked here we can just pass it recursively to some other types like state here and it will infer all of those things recursively through layers.
So that delivers a very nice dx because at every level of the state machine we can bind accepted types to only that level because at this level we can only transition to first or second state but we shouldn't be able, at least not with this syntax, we shouldn't be able to to transition to its children. So we shouldn't be able to transition to my child or my other child. So we can see that this specific transition is bound correctly and it's those are the only two valid valid values here and the autocompletes work nicely. In a similar manner, in in the nested transition only those states those sibling states can be used there as transition values. So we can't really transition from here to to the top level states first and second and the autocompletes are also correctly constrained to those valid ones here. There are some fixable limitations to this whole technique like they can only infer a single thing per object property or tuple element and there are some work in progress PRs that could address that intra expression inference also don't work within them or or other type parameters that appear within that reverse map type can't be I'm sorry let's pause.