Infer multiple things at once with reverse mapped types

Rate this content
Bookmark

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.

26 min
21 Sep, 2023

Video Summary and Transcription

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.

Available in Español

1. Introduction to Reverse Map Types

Short description:

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

Short description:

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

Short description:

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

Short description:

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.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

React Summit 2022React Summit 2022
20 min
Routing in React 18 and Beyond
Top Content
Concurrent React and Server Components are changing the way we think about routing, rendering, and fetching in web applications. Next.js recently shared part of its vision to help developers adopt these new React features and take advantage of the benefits they unlock.In this talk, we’ll explore the past, present and future of routing in front-end applications and discuss how new features in React and Next.js can help us architect more performant and feature-rich applications.
React Day Berlin 2023React Day Berlin 2023
21 min
React's Most Useful Types
Top Content
We don't think of React as shipping its own types. But React's types are a core part of the framework - overseen by the React team, and co-ordinated with React's major releases.In this live coding talk, we'll look at all the types you've been missing out on. How do you get the props type from a component? How do you know what ref a component takes? Should you use React.FC? And what's the deal with JSX.Element?You'll walk away with a bunch of exciting ideas to take to your React applications, and hopefully a new appreciation for the wonders of React and TypeScript working together.
Vue.js London 2023Vue.js London 2023
30 min
Stop Writing Your Routes
The more you keep working on an application, the more complicated its routing becomes, and the easier it is to make a mistake. ""Was the route named users or was it user?"", ""Did it have an id param or was it userId?"". If only TypeScript could tell you what are the possible names and params. If only you didn't have to write a single route anymore and let a plugin do it for you. In this talk we will go through what it took to bring automatically typed routes for Vue Router.
TypeScript Congress 2023TypeScript Congress 2023
31 min
Making Magic: Building a TypeScript-First Framework
I'll dive into the internals of Nuxt to describe how we've built a TypeScript-first framework that is deeply integrated with the user's IDE and type checking setup to offer end-to-end full-stack type safety, hints for layouts, middleware and more, typed runtime configuration options and even typed routing. Plus, I'll highlight what I'm most excited about doing in the days to come and how TypeScript makes that possible not just for us but for any library author.
React Advanced Conference 2021React Advanced Conference 2021
6 min
Full-stack & typesafe React (+Native) apps with tRPC.io
Top Content
Why are we devs so obsessed with decoupling things that are coupled nature? tRPC is a library that replaces the need for GraphQL or REST for internal APIs. When using it, you simply write backend functions whose input and output shapes are instantly inferred in your frontend without any code generation; making writing API schemas a thing of the past. It's lightweight, not tied to React, HTTP-cacheable, and can be incrementally adopted. In this talk, I'll give a glimpse of the DX you can get from tRPC and how (and why) to get started.

Workshops on related topic

React Advanced Conference 2021React Advanced Conference 2021
174 min
React, TypeScript, and TDD
Top Content
Featured WorkshopFree
ReactJS is wildly popular and thus wildly supported. TypeScript is increasingly popular, and thus increasingly supported.

The two together? Not as much. Given that they both change quickly, it's hard to find accurate learning materials.

React+TypeScript, with JetBrains IDEs? That three-part combination is the topic of this series. We'll show a little about a lot. Meaning, the key steps to getting productive, in the IDE, for React projects using TypeScript. Along the way we'll show test-driven development and emphasize tips-and-tricks in the IDE.
React Advanced Conference 2022React Advanced Conference 2022
148 min
Best Practices and Advanced TypeScript Tips for React Developers
Top Content
Featured Workshop
Are you a React developer trying to get the most benefits from TypeScript? Then this is the workshop for you.In this interactive workshop, we will start at the basics and examine the pros and cons of different ways you can declare React components using TypeScript. After that we will move to more advanced concepts where we will go beyond the strict setting of TypeScript. You will learn when to use types like any, unknown and never. We will explore the use of type predicates, guards and exhaustive checking. You will learn about the built-in mapped types as well as how to create your own new type map utilities. And we will start programming in the TypeScript type system using conditional types and type inferring.
Node Congress 2024Node Congress 2024
83 min
Deep TypeScript Tips & Tricks
Top Content
Workshop
TypeScript has a powerful type system with all sorts of fancy features for representing wild and wacky JavaScript states. But the syntax to do so isn't always straightforward, and the error messages aren't always precise in telling you what's wrong. Let's dive into how many of TypeScript's more powerful features really work, what kinds of real-world problems they solve, and how to wrestle the type system into submission so you can write truly excellent TypeScript code.
TypeScript Congress 2023TypeScript Congress 2023
131 min
Practice TypeScript Techniques Building React Server Components App
Workshop
In this hands-on workshop, Maurice will personally guide you through a series of exercises designed to empower you with a deep understanding of React Server Components and the power of TypeScript. Discover how to optimize your applications, improve performance, and unlock new possibilities.
 
During the workshop, you will:
- Maximize code maintainability and scalability with advanced TypeScript practices
- Unleash the performance benefits of React Server Components, surpassing traditional approaches
- Turbocharge your TypeScript with the power of Mapped Types
- Make your TypeScript types more secure with Opaque Types
- Explore the power of Template Literal Types when using Mapped Types
 
Maurice will virtually be by your side, offering comprehensive guidance and answering your questions as you navigate each exercise. By the end of the workshop, you'll have mastered React Server Components, armed with a newfound arsenal of TypeScript knowledge to supercharge your React applications.
 
Don't miss this opportunity to elevate your React expertise to new heights. Join our workshop and unlock the potential of React Server Components with TypeScript. Your apps will thank you.
TypeScript Congress 2022TypeScript Congress 2022
116 min
Advanced TypeScript types for fun and reliability
Workshop
If you're looking to get the most out of TypeScript, this workshop is for you! In this interactive workshop, we will explore the use of advanced types to improve the safety and predictability of your TypeScript code. You will learn when to use types like unknown or never. We will explore the use of type predicates, guards and exhaustive checking to make your TypeScript code more reliable both at compile and run-time. You will learn about the built-in mapped types as well as how to create your own new type map utilities. And we will start programming in the TypeScript type system using conditional types and type inferring.
Are you familiar with the basics of TypeScript and want to dive deeper? Then please join me with your laptop in this advanced and interactive workshop to learn all these topics and more.
You can find the slides, with links, here: http://theproblemsolver.nl/docs/ts-advanced-workshop.pdf
And the repository we will be using is here: https://github.com/mauricedb/ts-advanced
TestJS Summit 2023TestJS Summit 2023
78 min
Mastering Node.js Test Runner
Workshop
Node.js test runner is modern, fast, and doesn't require additional libraries, but understanding and using it well can be tricky. You will learn how to use Node.js test runner to its full potential. We'll show you how it compares to other tools, how to set it up, and how to run your tests effectively. During the workshop, we'll do exercises to help you get comfortable with filtering, using native assertions, running tests in parallel, using CLI, and more. We'll also talk about working with TypeScript, making custom reports, and code coverage.