Infer multiple things at once with reverse mapped types

Rate this content
Bookmark
This video covers the practical use of reverse map types in TypeScript, starting with the promiseify type-level function. It explains how reverse map types can help in inferring input types from known transformations and outputs. The talk also delves into the use of these types in state machines, ensuring that transitions and initial states are correctly typed. There's a focus on improving developer experience by binding event listeners to specific event types and reducing the complexity of function signatures. The video also highlights the benefits of using reverse map types for better type inference in complex objects, particularly in the context of state machines and event handling. The speaker discusses the utility of map types and reverse map types in transforming object property values and keys, making TypeScript more powerful for developers.

From Author:

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.

This talk has been presented at TypeScript Congress 2023, check out the latest edition of this Tech Conference.

FAQ

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.

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.

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.

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.

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.

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

Comments

Sign in or register to post your comment.

Video Transcription

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.

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 Conference 2022React Advanced Conference 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
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 Conference 2021React Advanced Conference 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.
Best Practices and Advanced TypeScript Tips for React Developers
React Advanced Conference 2022React Advanced Conference 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.
Master JavaScript Patterns
JSNation 2024JSNation 2024
145 min
Master JavaScript Patterns
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
Building Your Own Custom Type System
React Summit 2024React Summit 2024
38 min
Building Your Own Custom Type System
Featured Workshop
Kunal Dubey
Kunal Dubey
I'll introduce the audience to a concept where they can have end-to-end type systems that helps ensure typesafety across the teams Such a system not only improves communication between teams but also helps teams collaborate effectively and ship way faster than they used to before. By having a custom type system, teams can also identify the errors and modify the API contracts on their IDE, which contributes to a better Developer Experience. The workshop would primarily leverage TS to showcase the concept and use tools like OpenAPI to generate the typesystem on the client side.