Generating types without climbing a tree

Rate this content
Bookmark

How do you generate types dynamically? How do you write a script that creates some typescript code? The approach most people would recommend is to use Abstract Syntax Tree manipulations. I was working on a deadline to implement types for our OpenAPI client, and I would have missed our release window. I needed something different and easier to build. Luckily, a friend recommended me a library I didn't know: code-block-writer. I fall in love with it at first sight.

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

FAQ

Platformatic aims to simplify the process of creating back-end software by providing guardrails that allow developers to move quickly from development to production, reducing the undifferentiated heavy lifting of building JavaScript apps.

Platformatic uses the OpenAPI specification to automatically generate client codes, allowing developers to easily consume APIs without runtime data validation, ensuring a snappy performance and maintaining type safety.

Matteo Collina is the co-founder and CTO of Platformatic, a member of the Node.js Technical Steering Committee, and a board member of the Open Source Open JS Foundation. He has created and maintains numerous modules on NPM, with his software being downloaded over 17 billion times last year.

Fastify is a project that focuses on building APIs and is part of the Open Source Foundation. It is also used as a basis for Platformatic's developer experience for companies, aiming to simplify and improve how back-end software is created.

OpenAPI allows Platformatic to generate minimal and simple client codes from API specifications, which are compatible with any OpenAPI system. This provides a good developer experience by generating code that can be easily integrated and used.

Matteo Collina started using TypeScript in 2022 as a necessity when he started a new company focused on improving the developer experience for companies. This required him to delve into TypeScript despite having avoided the technology previously.

In software development, generating types involves creating type definitions automatically based on data structures or API specifications. This helps ensure type safety and can reduce errors by catching them during the development phase, before the software is executed.

Matteo Collina
Matteo Collina
30 min
21 Sep, 2023

Comments

Sign in or register to post your comment.

Video Summary and Transcription

This talk explores the challenges and benefits of generating types for APIs. The speaker discusses the need for a better client experience and the popularity of generating clients. They also explain the use of OpenAPI for generating REST API clients and the use of Cold Block Writer for code generation. The talk covers the process of defining types for parameters and responses, generating the client and request, and using the generated client. The speaker also touches on validation in production and the initial challenges with TypeScript.

1. Introduction to Generating Types

Short description:

Hi, everyone. I'm Matteo Collina, Platformatic Co-founder and CTO, and today I'm going to talk about something that makes me a little bit nervous, generating types. Entries. Why? Let's dig into it. So, the first question for all of you is, how many ropes do you need to climb a tree? This is a fundamental question and we are going to try to answer that question in this talk.

Hi, everyone. I'm Matteo Collina, Platformatic Co-founder and CTO, and today I'm going to talk about something that makes me a little bit nervous, generating types. Entries. Why? Let's dig into it. So, the first question for all of you is, how many ropes do you need to climb a tree? This is a fundamental question and we are going to try to answer that question in this talk. So, let's go.

First thing, a couple of things about me. I am Matteo Collina, part of the Node.js Technical Steering Committee, also board member of the Open Source Open JS Foundation. I created a bunch of libraries, help maintaining nodes, probably using some of my software given it's been downloaded 17 billion times last year, so yeah, maybe. So, some of my decisions impact a few people, so hopefully I don't break too many of you during this talk or otherwise.

So anyway, let's go and let's jump. So, I wrote a lot of modules, I maintain a lot of modules on NPM, a lot of downloads, whatever that matters. By the way, if you ever use one of those, if you want to send me a GitHub sponsor, everything is appreciated. I have a little bit of a small confession to make. What? What? Well, before 2022, I almost never used TypeScript. And here I'm speaking at TypeScript Congress. So what is that? It's really fascinating. I completely skimmed and avoid this technology for as long as I could. What happened in 2022? Well, I started a new company, and it was a developer experience for companies. So yeah, I kind of had to dig into TypeScript. In fact, it's all based on something I'd previously done, which is Fastify, which is a project inside the Open Source Foundation too. And it's all about building APIs. I'm a back-end engineer by trade and what I want to help people and how to help people with my tool, you know, to build and use APIs better and make it faster and make them easier to develop, maintain, scale, whatever you name it. So yeah, typically the typical flow of when one of your team members or somebody else is starting writing your APIs, you have an API on one end and you are typically a back-end engineer writing some complex SQL or some complex MongoDB queries, whatever you want to like, then they generate, write some documentation from that API and then your client, your engineer, code their client. So, okay, how does it make to generating the types? Yes, let me introduce the problem first. So, this is more or less what Plasformatic wants to simplify and improve how we create back-end software. Typically what we want to do is we want to move, allow you to move very quickly from A to B using as much rails as possible, guard rails for all of you to move very fast. And then, you know, you can get your old SUV to go where exactly you want to go. So, we want to help developers get rid of all the undifferentiated heavy lifting of building your JS apps. So, as part of that, we, at some point, we started focusing after we worked a lot on APIs and improve on two APIs that had been written.

2. The Need for a Better Client Experience

Short description:

What we found out from talking to a lot of people was that having a client for APIs was fundamental for a good development experience. Generating clients has become popular recently with libraries like tRPC and TS Rest. However, these libraries introduce tight coupling between the client and server code, making it difficult to scale and evolve. We need a better client experience that allows for flexibility and the use of different versions of TypeScript.

What we found out from talking to a lot of people was that, you know, oh, but having a client for those APIs was actually fundamental for providing a good experience and streamlining the development. So, what happened was that, you know, most people really like this flow much better. So, instead of having to call the client and prepare documentation for the API, I just want to hit a button and generate a client.

In fact, this has been so popular for ages, and kind of we got it lost a little bit along the way, because, you know, I remember generating clients for my APIs when I was doing WSDL and SOAP a long time ago. So, you know, probably not a great comparison, but it is. So, anyway, this has been extremely popular recently. In fact, this has been popularized a lot by a few new libraries. One is tRPC, which is fantastic, provides a fantastic developer experience. It allows you to expose your... creates an RPC call from the server to the... from the client to the server in a completely type-safe way. It's great, okay? It has only one significant drawback, which is introduced type coupling within your... the code of your frontend with the code of your backend, it also uses a proprietary protocol to communicate. So yeah, it's very tight. It's a very tight coupling between client and server. There is another library called TS Rest, which is also great, fantastic library, but it has another small... still another small problem, which is you need to specify the contract between your client and your server at its own typescape definition. Again, in order to consume the library, you need to have a source code dependency on the server. So again, for me, it provides introduced tight coupling between those two.

In fact, the problem here is the concept of you know, what happens in most teams that I have worked and developed with and so on, it's that you have basically some API that is developed by more or less a team and there is another group of people that you know, creates and consumes or that consumes those APIs. And those groups typically are more or less separated in most companies and in most organizations. So, integrating everything together, create a tight coupling between everything that makes it very hard to break down and scale and keep evolving things. And by the way, there is nothing to be taken by those libraries, which are fantastic. I'm just talking about what I am not, some of the reasons why I think we need a better client experience for APIs. So what, where are we left? Well, something that we want to provide some fantastic developer experience but without any tight coupling. So, without any code being shared, essentially, between the server and the client, so that you can essentially use and consume other APIs. And so, that one can use TypeScript 4.9 and the other one can use TypeScript 6 in the future. And they can evolve and have different versions, different things. Everything is fun and perfect. And so, how can we generate this developer experience? I started this journey, one of my journey types of work with this question.

QnA

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

Scaling Up with Remix and Micro Frontends
Remix Conf Europe 2022Remix Conf Europe 2022
23 min
Scaling Up with Remix and Micro Frontends
Top Content
This talk discusses the usage of Microfrontends in Remix and introduces the Tiny Frontend library. Kazoo, a used car buying platform, follows a domain-driven design approach and encountered issues with granular slicing. Tiny Frontend aims to solve the slicing problem and promotes type safety and compatibility of shared dependencies. The speaker demonstrates how Tiny Frontend works with server-side rendering and how Remix can consume and update components without redeploying the app. The talk also explores the usage of micro frontends and the future support for Webpack Module Federation in Remix.
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.
Full Stack Components
Remix Conf Europe 2022Remix Conf Europe 2022
37 min
Full Stack Components
Top Content
RemixConf EU discussed full stack components and their benefits, such as marrying the backend and UI in the same file. The talk demonstrated the implementation of a combo box with search functionality using Remix and the Downshift library. It also highlighted the ease of creating resource routes in Remix and the importance of code organization and maintainability in full stack components. The speaker expressed gratitude towards the audience and discussed the future of Remix, including its acquisition by Shopify and the potential for collaboration with Hydrogen.
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.
Debugging JS
React Summit 2023React Summit 2023
24 min
Debugging JS
Top Content
Watch video: Debugging JS
Debugging JavaScript is a crucial skill that is often overlooked in the industry. It is important to understand the problem, reproduce the issue, and identify the root cause. Having a variety of debugging tools and techniques, such as console methods and graphical debuggers, is beneficial. Replay is a time-traveling debugger for JavaScript that allows users to record and inspect bugs. It works with Redux, plain React, and even minified code with the help of source maps.
Making JavaScript on WebAssembly Fast
JSNation Live 2021JSNation Live 2021
29 min
Making JavaScript on WebAssembly Fast
Top Content
WebAssembly enables optimizing JavaScript performance for different environments by deploying the JavaScript engine as a portable WebAssembly module. By making JavaScript on WebAssembly fast, instances can be created for each request, reducing latency and security risks. Initialization and runtime phases can be improved with tools like Wiser and snapshotting, resulting in faster startup times. Optimizing JavaScript performance in WebAssembly can be achieved through techniques like ahead-of-time compilation and inline caching. WebAssembly usage is growing outside the web, offering benefits like isolation and portability. Build sizes and snapshotting in WebAssembly depend on the application, and more information can be found on the Mozilla Hacks website and Bike Reliance site.

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.