The Potential of Higher-Kinded Types for Library Semantics

Rate this content
Bookmark

There is a wall that we all hit when developing more sophisticated types: how can I 'abstract out' certain commonalities in my type-level logic? How can I make my types more reusable and composable? How can I make my types more expressive?

This talk will introduce the fundamentals of Higher-Kinded Types, a compelling concept hitherto underutilized, and explore how they can significantly enhance the expressiveness of library semantics, leading to a more intuitive developer experience (DX). We'll demonstrate how HKTs can provide an elevated abstraction level, allowing you to model complex domain problems more naturally and in a type-safe manner.

Join us to understand how leveraging HKTs can elevate your TypeScript coding practice, optimizing the semantics and delivering a more potent and featureful library interface.

Michael Poteat
Michael Poteat
8 min
21 Sep, 2023

Comments

Sign in or register to post your comment.

Video Summary and Transcription

The Talk discusses the potential of higher kind of types (HKTs) for library semantics, enabling better inference and type-level operations. It explains how HKTs can be created in TypeScript by exploiting function types as a function of object attributes. This allows for the creation of composable functional utilities with intelligent type inference and a chaining interface that computes type-level results. Overall, the Talk highlights the benefits and possibilities of using HKTs in software development.

Available in Español

1. Introduction to Higher Kinda Types

Short description:

I'm excited to talk about the potential of higher kinda types for library semantics today. HKTs make better inference possible. We can use HKTs to represent type level operations and compose types together using functional semantics. Higher kind of types are types associated with a type constructor. We want to write code that applies an operation to a map and then applies it to an array, extracting the logic intrinsic to looping over an array and applying a transformation to each element.

Hey there, everyone. I'm excited to talk about the potential of higher kinda types for library semantics today, as part of the TypeScript Congress 2023 lightning talk. First, a little bit about myself. My name's Michael Potit. I'm an engineering manager at Volley, where we are creating the future of voice-enabled entertainment. I have a passion for type-level programming. I've created HKT Toolbelt, which we'll mention a little bit later. You can read about my programming on my blog at code.lol. And I'm excited to talk about the flexibility of higher kinda types in TypeScript today.

So, library semantics. What do we mean by this? So, we want the type system to infer as much about our code as possible. Often, libraries don't do it. So, in this code example, we're using Lodash. We are doing a chain on some sort of object. We're calculating the keys, and then we're mapping those keys to convert them all to uppercase. What we know the value to be is A, B, and C in uppercase, but Lodash just infers an array of strings. So, this is sometimes very inconvenient, and forces us to make explicit type declarations when we otherwise would not have to. So, HKTs basically make better inference possible. We can use HKTs to represent type level operations, and we can compose types together using functional semantics. We can do this so well that end users never have to write any sort of custom types themselves.

So, what are higher kind of types? Basically, a kind is a type associated with a type constructor. In TypeScript, you would know this as like type foo of T equals T, right? The simplest kind is just star, these are your base types. And the next simplest kind is star to star, which is your normal sort of one-erity generic. So, like, capitalize of S or promise of T, etc. So, TypeScript natively supports these two, but we want more. So, we would like to support, for example, a type that takes in a type, sort of generic itself, and a value which represents an array, and we want to loop over that array applying this type operation to each element. So, the kind associated with this would be this sort of complicated expression, which we need to do clever things to support in the TypeScript system. So, what are we actually trying to do? So, what we want to do is we want to write code like this, so we want to say we want to use this operator, or any sort of application operator, and say, oh, right. We want to apply the operation capitalize to map, so that we get map capitalize, which, you know, converts capitalize into something that can be mapped over an array, and then we want to apply that to an array to get a result. So, we're extracting out the logic intrinsic to looping over an array and applying a transformation to each element.

2. Creating Higher Kind of Types in TypeScript

Short description:

This is surprisingly possible in TypeScript. We exploit the fact that function types can be a function of object attributes. We can create functions that behave like higher kind of types. Using this, we can create composable functional utilities with intelligent type inference. We can also achieve a chaining interface that computes type-level results as operations are chained together. That's my lightning talk. Thank you for listening.

This is surprisingly possible in TypeScript. So, here's the minimum definition needed to create this rich set of higher kind of types. Basically, what's going on here is that we are exploiting the fact that on interfaces, the types of functions can be a function of attributes on the object. So, basically, what we're doing is we are filling in the parameter represented by the x element on line two and then extracting out the return type of f.

Here's an example of the identity sort of higher kind of type. What we say identity extends kind and then we just return type of x for the underlying sort of transformation we are representing. So, always the transformation is on the right-hand side.

This is a slightly more complicated example. We don't need to understand or walk through all of this, but essentially on line 11 here, we are applying append to this bar string, which creates a function that appends the string bar to any string that it's given and then we're passing in foo so we get foo bar. What you'll notice is that all arguments are curried in this new semantics. We can also do map, as I mentioned before. Again, we don't need to understand the entire logic here but notably what we're doing is we are taking this append function that we made earlier, we are sort of converting it to something that can be mapped over an array and then we are running it over an array so we get foo bar and baz bar.

All right, so that was a lot of code listings. The question would be, how do we actually use this in real programming? To do this, generally speaking, we want to use a process that I call kind ratification but basically we are bringing down a higher kind of type and we are giving it a callable interface so on line two we're saying the callable function is going to be a generic function that is an input of the kind associated with this type. We are inferring what that literal constant is going to be and then we are basically recursively executing that across all of the arguments that this higher kind of type is returning. I am not including the full implementation here but it's not much more complicated than this. And essentially what this allows us to do is to create functions which behave like higher kind of types.

So using this, we can create this reified map view including the implementation. So we have a map here very simple sort of curried map logic and then we say as reified map and then we have append which is just as reified append and then we can create this result expression where we are sort of mapping over an array with this append statement so that we get hello exclamation mark world exclamation mark. So we've created these composable functional utilities that are sort of that have intelligent type inference associated with them.

So up until now we've used point free semantics to write our code where whereby we're not explicitly mentioning any arguments to our functions but you know more often folks use fluent API design for example in lodash with their chaining semantics so we can actually that using HKTs not including the full implementation but what we want in the end is and what we can get is a chaining interface that actually computes the type level result as you are executing these operations and chaining these operations together. So what we infer in the end is A and B and C.

That's my lightning talk. Thank you so much for listening.

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

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
TypeScript and React are inseparable. What's the secret to their successful union? Quite a lot of surprisingly strange code. Learn why useRef always feels weird, how to wrangle generics in custom hooks, and how union types can transform your components.
Remix Flat Routes – An Evolution in Routing
Remix Conf Europe 2022Remix Conf Europe 2022
16 min
Remix Flat Routes – An Evolution in Routing
Top Content
This talk introduces the new Flat Routes convention that will most likely be the default in a future version of Remix. It simplifies the existing convention as well as gives you new capabilities.
React's Most Useful Types
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.
Stop Writing Your Routes
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.
Making Magic: Building a TypeScript-First Framework
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.
How to Make a Web Game All by Yourself
JS GameDev Summit 2023JS GameDev Summit 2023
27 min
How to Make a Web Game All by Yourself
It's never been easier to make your own web game, but it's still extremely difficult. What game should you make? Which engine should you choose? Let's discuss how to answer these problems and ways to leverage the unique platform that is the web.

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.
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.
Deep TypeScript Tips & Tricks
Node Congress 2024Node Congress 2024
83 min
Deep TypeScript Tips & Tricks
Top Content
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.
Practice TypeScript Techniques Building React Server Components App
TypeScript Congress 2023TypeScript Congress 2023
131 min
Practice TypeScript Techniques Building React Server Components App
Workshop
Maurice de Beijer
Maurice de Beijer
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.
Advanced TypeScript types for fun and reliability
TypeScript Congress 2022TypeScript Congress 2022
116 min
Advanced TypeScript types for fun and reliability
Workshop
Maurice de Beijer
Maurice de Beijer
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
Mastering Node.js Test Runner
TestJS Summit 2023TestJS Summit 2023
78 min
Mastering Node.js Test Runner
Workshop
Marco Ippolito
Marco Ippolito
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.