El Potencial de los Tipos de Mayor Orden para la Semántica de Bibliotecas

Rate this content
Bookmark

Hay un obstáculo con el que todos nos encontramos al desarrollar tipos más sofisticados: ¿cómo puedo 'abstraer' ciertas similitudes en mi lógica a nivel de tipos? ¿Cómo puedo hacer que mis tipos sean más reutilizables y componibles? ¿Cómo puedo hacer que mis tipos sean más expresivos?

Esta charla presentará los fundamentos de los Tipos de Mayor Orden, un concepto convincente hasta ahora subutilizado, y explorará cómo pueden mejorar significativamente la expresividad de la semántica de las bibliotecas, lo que conduce a una experiencia de desarrollo más intuitiva (DX). Demostraremos cómo los Tipos de Mayor Orden pueden proporcionar un nivel de abstracción elevado, lo que le permite modelar problemas de dominio complejos de manera más natural y de forma segura en cuanto a tipos.

Acompáñenos para comprender cómo aprovechar los Tipos de Mayor Orden puede elevar su práctica de codificación en TypeScript, optimizando la semántica y ofreciendo una interfaz de biblioteca más potente y completa.

Michael Poteat
Michael Poteat
8 min
21 Sep, 2023

Video Summary and Transcription

La charla analiza el potencial de los tipos de mayor orden (HKTs) para la semántica de bibliotecas, permitiendo una mejor inferencia y operaciones a nivel de tipos. Explica cómo se pueden crear HKTs en TypeScript aprovechando los tipos de función como una función de los atributos del objeto. Esto permite la creación de utilidades funcionales componibles con inferencia de tipos inteligente y una interfaz de encadenamiento que calcula resultados a nivel de tipos. En general, la charla destaca los beneficios y posibilidades de utilizar HKTs en el desarrollo de software.

Available in English

1. Introducción a los Higher Kinda Types

Short description:

Estoy emocionado de hablar sobre el potencial de los Higher Kinda Types para la semántica de las bibliotecas hoy. Los HKTs hacen posible una mejor inferencia. Podemos usar los HKTs para representar operaciones a nivel de tipos y componer tipos juntos utilizando semántica funcional. Los Higher Kinda Types son tipos asociados con un constructor de tipos. Queremos escribir código que aplique una operación a un mapa y luego la aplique a un array, extrayendo la lógica intrínseca de iterar sobre un array y aplicar una transformación a cada elemento.

¡Hola a todos! Estoy emocionado de hablar sobre el potencial de los Higher Kinda Types para la semántica de las bibliotecas hoy, como parte de la charla relámpago del Congreso de TypeScript 2023. Primero, un poco sobre mí. Mi nombre es Michael Potit. Soy gerente de ingeniería en Volley, donde estamos creando el futuro del entretenimiento habilitado para voz. Tengo pasión por la programación a nivel de tipos. He creado HKT Toolbelt, del cual hablaremos un poco más adelante. Pueden leer sobre mi programación en mi blog en code.lol. Y estoy emocionado de hablar sobre la flexibilidad de los Higher Kinda Types en TypeScript hoy. Entonces, semántica de bibliotecas. ¿Qué queremos decir con esto?

Queremos que el sistema de tipos infiera tanto como sea posible sobre nuestro código. A menudo, las bibliotecas no lo hacen. En este ejemplo de código, estamos usando Lodash. Estamos encadenando algunas operaciones en algún objeto. Estamos calculando las claves y luego mapeando esas claves para convertirlas todas en mayúsculas. Lo que sabemos que el valor debería ser es A, B y C en mayúsculas, pero Lodash solo infiere un array de strings. Esto a veces es muy incómodo y nos obliga a hacer declaraciones de tipos explícitas cuando de otra manera no tendríamos que hacerlo.

Entonces, los HKTs básicamente hacen posible una mejor inferencia. Podemos usar los HKTs para representar operaciones a nivel de tipos y podemos componer tipos juntos utilizando semántica funcional. Podemos hacer esto tan bien que los usuarios finales nunca tienen que escribir ningún tipo personalizado ellos mismos. Entonces, ¿qué son los Higher Kinda Types?

Básicamente, un kind es un tipo asociado con un constructor de tipos. En TypeScript, esto sería como el tipo foo de T es igual a T, ¿verdad? El kind más simple es simplemente star, que son tus tipos base. Y el kind siguiente más simple es star a star, que es tu tipo genérico de aridad uno normal. Entonces, capitalize de S o promise de T, etc. TypeScript admite nativamente estos dos, pero queremos más. Por ejemplo, nos gustaría admitir un tipo que reciba un tipo, genérico en sí mismo, y un valor que represente un array, y queremos iterar sobre ese array aplicando esta operación de tipo a cada elemento. Entonces, el kind asociado con esto sería esta expresión complicada, para la cual necesitamos hacer cosas inteligentes para admitirla en el sistema de TypeScript.

Entonces, ¿qué estamos tratando de hacer realmente? Lo que queremos hacer es escribir código como este, queremos decir que queremos usar este operador, o cualquier tipo de operador de aplicación, y decir, ah, sí. Queremos aplicar la operación capitalize a map, para que obtengamos map capitalize, que convierte capitalize en algo que se puede mapear sobre un array, y luego queremos aplicarlo a un array para obtener un resultado. Estamos extrayendo la lógica intrínseca de iterar sobre un array y aplicar una transformación a cada elemento.

2. Creando Higher Kind of Types en TypeScript

Short description:

Esto es sorprendentemente posible en TypeScript. Explotamos el hecho de que los tipos de función pueden ser una función de los atributos del objeto. Podemos crear funciones que se comporten como higher kind of types. Usando esto, podemos crear utilidades funcionales componibles con inferencia de tipos inteligente. También podemos lograr una interfaz encadenada que calcula resultados a nivel de tipos a medida que se encadenan las operaciones. Esa es mi charla relámpago. Gracias por escuchar.

Esto es sorprendentemente posible en TypeScript. Entonces, aquí está la definición mínima necesaria para crear este rico conjunto de higher kind of types. Básicamente, lo que está sucediendo aquí es que estamos explotando el hecho de que en las interfaces, los tipos de funciones pueden ser una función de los atributos del objeto. Entonces, básicamente, lo que estamos haciendo es llenar el parámetro representado por el elemento x en la línea dos y luego extraer el tipo de retorno de f. Como vimos antes, si aplicamos, por ejemplo, la función de identidad a uno, obtendríamos simplemente uno. Aquí hay un ejemplo del tipo de higher kind de identidad. Decimos que identity extiende kind y luego devolvemos el tipo de x para la transformación subyacente que estamos representando. Siempre la transformación está en el lado derecho. Este es un ejemplo un poco más complicado. No necesitamos entender o recorrer todo esto, pero básicamente en la línea 11 aquí, estamos aplicando append a esta cadena bar, lo que crea una función que agrega la cadena bar a cualquier cadena que se le dé, y luego pasamos foo para obtener foo bar. Lo que notarán es que todos los argumentos están currificados en esta nueva semántica. También podemos hacer map, como mencioné antes. Nuevamente, no necesitamos entender toda la lógica aquí, pero notablemente lo que estamos haciendo es tomar esta función append que hicimos antes, convertirla en algo que se pueda mapear sobre un array y luego ejecutarla sobre un array para obtener foo bar y baz bar. Bueno, eso fue mucho código. La pregunta sería, ¿cómo lo usamos realmente en la programación real? Para hacer esto, en general, queremos usar un proceso que llamo ratificación de kind, pero básicamente estamos bajando un higher kind of type y le estamos dando una interfaz callable, por lo que en la línea dos decimos que la función callable va a ser una función genérica que es una entrada del tipo asociado con este tipo. Inferimos qué constante literal va a ser y luego ejecutamos recursivamente eso en todos los argumentos que este higher kind of type está devolviendo. No incluyo la implementación completa aquí, pero no es mucho más complicada que esto. Y básicamente lo que esto nos permite hacer es crear funciones que se comporten como higher kind of types. Entonces, usando esto, podemos crear esta vista de mapa reificada que incluye la implementación. Tenemos un mapa aquí, una lógica de mapa currificada muy simple, y luego decimos como mapa reificado y luego tenemos append que es simplemente como append reificado y luego podemos crear esta expresión de resultado donde estamos mapeando sobre un array con esta declaración de append para que obtengamos hello exclamation mark world exclamation mark. Entonces hemos creado estas utilidades funcionales componibles que tienen inferencia de tipos inteligente asociada.

Hasta ahora hemos utilizado la semántica point free para escribir nuestro código, donde no mencionamos explícitamente ningún argumento en nuestras funciones, pero a menudo las personas usan una API fluida, por ejemplo en lodash, con su semántica de encadenamiento, por lo que podemos hacer eso usando HKTs sin incluir la implementación completa, pero lo que queremos al final y lo que podemos obtener es una interfaz encadenada que realmente calcula el resultado a nivel de tipos a medida que se ejecutan y se encadenan estas operaciones. Entonces, lo que inferimos al final es A y B y C. Esa es mi charla relámpago. Muchas gracias por escuchar. Por favor, salgan y mejoren el ecosistema de TypeScript escribiendo bibliotecas que usen higher kind of types.

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.