Infer multiple things at once with reverse mapped types

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.

Rate this content
Bookmark
Video Summary and Transcription
The video explores the concept of reverse map types in TypeScript, highlighting their role in inferring input types based on known transformations and outputs. It delves into the 'promiseify' type-level function, which wraps a key of a type with a function that returns a promise. This transformation is significant for asynchronous operations, allowing regular functions to return Promises. The talk covers the application of reverse map types in state machines, ensuring transitions and initial states are accurately typed and constrained to valid configurations. An example is provided on how reverse map types can improve event management by associating specific event types with their respective listeners, enhancing accuracy and developer experience. The discussion also touches on how mapped types in TypeScript transform object property values and keys, which is useful in various coding scenarios. The video emphasizes the utility of these types in refining type inference, especially when dealing with complex objects, thereby improving code readability and safety.

FAQ

The 'promiseify' type level function in TypeScript iterates over the keys of a type 't' and wraps each property type in a function that returns a Promise of that type. This transformation is used to convert regular functions or methods into ones that return Promises, suitable for asynchronous operations.

Map types in TypeScript are type-level functions that accept a union of keys and output an object type. They are useful for transforming object property values and, since TypeScript 4.1, also for transforming object property keys.

Mateusz Kruzynski is a professional working at Stately, focusing on state machines and related technologies. He also maintains popular open source projects such as Emotion, Redux Saga, ChangeSets, and XState, and contributes to TypeScript.

The 'satisfy object name' function in TypeScript utilizes a type-level function to infer the types of object keys. It helps in resolving keys for parameter types to match the keys themselves, facilitating more precise type inference in complex objects.

Reverse map types can be utilized in state machines to ensure that transitions and initial states are correctly typed and constrained to valid configurations. This application enhances safety and predictability in state management by enforcing type correctness at compile time.

Reverse map types in TypeScript are used to determine the required input type that results in a specific output type after a transformation. They are particularly useful for inferring input types based on known transformations and outputs, aiding in type inference.

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.

Mateusz Burzyński
Mateusz Burzyński
26 min
21 Sep, 2023

Comments

Sign in or register to post your comment.

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

Routing in React 18 and Beyond
React Summit 2022React Summit 2022
20 min
Routing in React 18 and Beyond
Top Content
Routing in React 18 brings a native app-like user experience and allows applications to transition between different environments. React Router and Next.js have different approaches to routing, with React Router using component-based routing and Next.js using file system-based routing. React server components provide the primitives to address the disadvantages of multipage applications while maintaining the same user experience. Improving navigation and routing in React involves including loading UI, pre-rendering parts of the screen, and using server components for more performant experiences. Next.js and Remix are moving towards a converging solution by combining component-based routing with file system routing.
React's Most Useful Types
React Day Berlin 2023React Day Berlin 2023
21 min
React's Most Useful Types
Top Content
Watch video: React's Most Useful Types
Today's Talk focuses on React's best types and JSX. It covers the types of JSX and React components, including React.fc and React.reactnode. The discussion also explores JSX intrinsic elements and react.component props, highlighting their differences and use cases. The Talk concludes with insights on using React.componentType and passing components, as well as utilizing the react.element ref type for external libraries like React-Select.
TypeScript and React: Secrets of a Happy Marriage
React Advanced 2022React Advanced 2022
21 min
TypeScript and React: Secrets of a Happy Marriage
Top Content
React and TypeScript have a strong relationship, with TypeScript offering benefits like better type checking and contract enforcement. Failing early and failing hard is important in software development to catch errors and debug effectively. TypeScript provides early detection of errors and ensures data accuracy in components and hooks. It offers superior type safety but can become complex as the codebase grows. Using union types in props can resolve errors and address dependencies. Dynamic communication and type contracts can be achieved through generics. Understanding React's built-in types and hooks like useState and useRef is crucial for leveraging their functionality.
Making Magic: Building a TypeScript-First Framework
TypeScript Congress 2023TypeScript Congress 2023
31 min
Making Magic: Building a TypeScript-First Framework
Top Content
Daniel Rowe discusses building a TypeScript-first framework at TypeScript Congress and shares his involvement in various projects. Nuxt is a progressive framework built on Vue.js, aiming to reduce friction and distraction for developers. It leverages TypeScript for inference and aims to be the source of truth for projects. Nuxt provides type safety and extensibility through integration with TypeScript. Migrating to TypeScript offers long-term maintenance benefits and can uncover hidden bugs. Nuxt focuses on improving existing tools and finds inspiration in frameworks like TRPC.
Stop Writing Your Routes
Vue.js London 2023Vue.js London 2023
30 min
Stop Writing Your Routes
Top Content
Designing APIs is a challenge, and it's important to consider the language used and different versions of the API. API ergonomics focus on ease of use and trade-offs. Routing is a misunderstood aspect of API design, and file-based routing can simplify it. Unplugging View Router provides typed routes and eliminates the need to pass routes when creating the router. Data loading and handling can be improved with data loaders and predictable routes. Handling protected routes and index and ID files are also discussed.
Faster TypeScript builds with --isolatedDeclarations
TypeScript Congress 2023TypeScript Congress 2023
24 min
Faster TypeScript builds with --isolatedDeclarations
Top Content
This talk discusses the performance issues in TypeScript builds and introduces a new feature called isolated declarations. By running the compiler in parallel and using isolated modules, significant performance gains can be achieved. Isolated declarations improve build speed, compatibility with other tools, and require developers to write types in code. This feature has the potential to further increase performance and may be available in TypeScript soon.

Workshops on related topic

React, TypeScript, and TDD
React Advanced 2021React Advanced 2021
174 min
React, TypeScript, and TDD
Top Content
Featured WorkshopFree
Paul Everitt
Paul Everitt
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.
Mastering advanced concepts in TypeScript
React Summit US 2023React Summit US 2023
132 min
Mastering advanced concepts in TypeScript
Top Content
Featured WorkshopFree
Jiri Lojda
Jiri Lojda
TypeScript is not just types and interfaces. Join this workshop to master more advanced features of TypeScript that will make your code bullet-proof. We will cover conditional types and infer notation, template strings and how to map over union types and object/array properties. Each topic will be demonstrated on a sample application that was written with basic types or no types at all and we will together improve the code so you get more familiar with each feature and can bring this new knowledge directly into your projects.
You will learn:- - What are conditional types and infer notation- What are template strings- How to map over union types and object/array properties.
Deep TypeScript Tips & Tricks
Node Congress 2024Node Congress 2024
83 min
Deep TypeScript Tips & Tricks
Top Content
Featured Workshop
Josh Goldberg
Josh Goldberg
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.
Master JavaScript Patterns
JSNation 2024JSNation 2024
145 min
Master JavaScript Patterns
Top Content
Featured Workshop
Adrian Hajdin
Adrian Hajdin
During this workshop, participants will review the essential JavaScript patterns that every developer should know. Through hands-on exercises, real-world examples, and interactive discussions, attendees will deepen their understanding of best practices for organizing code, solving common challenges, and designing scalable architectures. By the end of the workshop, participants will gain newfound confidence in their ability to write high-quality JavaScript code that stands the test of time.
Points Covered:
1. Introduction to JavaScript Patterns2. Foundational Patterns3. Object Creation Patterns4. Behavioral Patterns5. Architectural Patterns6. Hands-On Exercises and Case Studies
How It Will Help Developers:
- Gain a deep understanding of JavaScript patterns and their applications in real-world scenarios- Learn best practices for organizing code, solving common challenges, and designing scalable architectures- Enhance problem-solving skills and code readability- Improve collaboration and communication within development teams- Accelerate career growth and opportunities for advancement in the software industry
Best Practices and Advanced TypeScript Tips for React Developers
React Advanced 2022React Advanced 2022
148 min
Best Practices and Advanced TypeScript Tips for React Developers
Top Content
Featured Workshop
Maurice de Beijer
Maurice de Beijer
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.
React Patterns Made Simple
React Day Berlin 2024React Day Berlin 2024
62 min
React Patterns Made Simple
Featured Workshop
Adrian Hajdin
Adrian Hajdin
Learn widely used React patterns, including HOCs, Compound Components, Provider Patterns, Functions as Child, and Portals, to write cleaner, more efficient code and create scalable, maintainable applications.Overview In this workshop, viewers will learn about key React patterns that can make their code more efficient, readable, and maintainable. We'll introduce each pattern, explain how it works, and demonstrate practical examples. By the end of the session, participants will have a solid understanding of how to use these patterns in their projects.Learning GoalsHOCs Compound Components Provider Patterns Functions as Child Portals Modularity Maintainability Real-world Application.