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

Comments

Sign in or register to post your comment.

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

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
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.
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
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.
TypeScript Congress 2022TypeScript Congress 2022
10 min
How to properly handle URL slug changes in Next.js
If you're using a headless CMS for storing content, you also work with URL slugs, the last parts of any URL. The problem is, content editors are able to freely change the slugs which can cause 404 errors, lost page ranks, broken links, and in the end confused visitors on your site. In this talk, I will present a solution for keeping a history of URL slugs in the CMS and explain how to implement a proper redirect mechanism (using TypeScript!) for dynamically generated pages on a Next.js website.
Add to the talk notes: https://github.com/ondrabus/kontent-boilerplate-next-js-ts-congress-2022 

Workshops on related topic

React Advanced Conference 2021React Advanced Conference 2021
174 min
React, TypeScript, and TDD
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
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.
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
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.
Node Congress 2021Node Congress 2021
245 min
Building Serverless Applications on AWS with TypeScript
Workshop
This workshop teaches you the basics of serverless application development with TypeScript. We'll start with a simple Lambda function, set up the project and the infrastructure-as-a-code (AWS CDK), and learn how to organize, test, and debug a more complex serverless application.
Table of contents:
        - How to set up a serverless project with TypeScript and CDK
        - How to write a testable Lambda function with hexagonal architecture
        - How to connect a function to a DynamoDB table
        - How to create a serverless API
        - How to debug and test a serverless function
        - How to organize and grow a serverless application
Materials referred to in the workshop:
https://excalidraw.com/#room=57b84e0df9bdb7ea5675,HYgVepLIpfxrK4EQNclQ9w
DynamoDB blog Alex DeBrie: https://www.dynamodbguide.com/
Excellent book for the DynamoDB: 
https://www.dynamodbbook.com/
https://slobodan.me/workshops/nodecongress/prerequisites.html


TypeScript Congress 2022TypeScript Congress 2022
118 min
Crash Course into TypeScript for content from headless CMS
WorkshopFree
In this workshop, I’ll first show you how to create a new project in a headless CMS, fill it with data, and use the content in your project. Then, we’ll spend the rest of time in code, we will:
- Generate strongly typed models and structure for the fetched content.
- Use the content in components
- Resolve content from rich text fields into React components
- Touch on deployment pipelines and possibilities for discovering content-related issues before hitting production