Generating TypeScript with TypeScript

Rate this content
Bookmark

A deep-dive into how we automatically generate TypeScript definitions for the V8-based runtime that powers Cloudflare Workers. We'll give an overview of how we use the TypeScript compiler API, how we enhance auto-generated definitions with user-written overrides to improve ergonomics, and how we created a service to build types for users' specific compatibility settings.

This talk has been presented at DevOps.js Conf 2024, check out the latest edition of this Tech Conference.

FAQ

CloudFlare Workers are a functions-as-a-service platform where you write HTTP handling code, publish it, and get a URL to run it. Your code is deployed to all CloudFlare edge locations for low latency access.

CloudFlare Workers offer low latency access by deploying code to edge locations, practically no cold start time due to V8 isolates, and both standard and nonstandard web APIs for server-side use cases.

Type checking prevents errors at runtime and provides auto-completion in Integrated Development Environments (IDEs), improving developer productivity and code reliability.

Types were handwritten and included only CloudFlare-specific APIs, not web standards. This approach was error-prone, slow to update with new APIs, and relied on libwebworker, which included APIs not implemented by CloudFlare Workers.

Runtime type information allows querying types at runtime and is encoded as cap'n proto, a language and platform-independent binary format. It helps in auto-generating TypeScript definitions by converting runtime API types into TypeScript.

The process starts by encoding all runtime API types in C++ and then performing further processing in TypeScript using the TypeScript compiler API. This method automatically generates TypeScript definitions from runtime type information.

Transformations include fixing iterators, extracting global scope members, and adding function overloads with human input. These transformations ensure TypeScript recognizes all necessary information for accurate type definitions.

Manual type overrides are inserted alongside C++ code and encoded with runtime type information in cap'n proto. This approach allows runtime developers to add and update overrides easily, improving developer ergonomics.

A compatibility date specifies when breaking changes are enabled by default. It helps prevent breaking existing deployed code by putting breaking changes behind compatibility flags.

The planned solution is to build Types as a Service, a CloudFlare Worker that dynamically generates NPM packages containing TypeScript definition files based on the selected compatibility date and flags.

Brendan Coll
Brendan Coll
8 min
15 Feb, 2024

Comments

Sign in or register to post your comment.

Video Summary and Transcription

This talk discusses how TypeScript definitions are automatically generated for CloudFlare workers using runtime type information. The encoding and transformation of type information is explained, with runtime API types being encoded in C++ and further processed in TypeScript. The process of improving type definitions and achieving compatibility is also covered, including fixing problems with iterators and using human input to improve developer ergonomics. The talk concludes with a plan to build Types as a Service, a Cloudflare worker that dynamically generates NPM packages containing TypeScript definition files.

1. Introduction to CloudFlare Workers

Short description:

In this part, I will discuss how we automatically generate TypeScript definitions for CloudFlare workers using TypeScript. We will cover the problems with the handwritten types approach we used a few years ago, our auto generation approach using runtime type information, transformations to improve other types, manual type overrides to improve developer ergonomics, and compatibility dates. We will also explore the workers runtime's run time type information system.

Hello, everyone. Welcome to my talk on how we automatically generate TypeScript definitions for CloudFlare workers using TypeScript.

As a quick introduction, I'm Brendan. I created MiniFlare, a fully local simulator for CloudFlare workers. I mentioned CloudFlare workers a few times already, but what are they? Workers are functions as a service platform. You write some HTTP handling code, publish it to our platform, and we give you a URL you can hit to run it. We deploy your code to all CloudFlare edge locations so your users get low latency access wherever they are. Importantly, there's practically no cold start time. Because our run time is based on V8 isolates, not containers or virtual machines. In addition to standard web APIs, we provide nonstandard APIs for key value storage.

The key points that we've got so far are custom V8 run time based like Node or Dino. We implement mostly web standard APIs like browsers, but also implement some nonstandard APIs specifically for server-side use cases. With all this in mind, why do we want types? We want type checking to prevent errors at run time and we want auto completion in IDEs. To start, we'll cover how we used to do handwritten types a couple years ago, then we'll look at our auto generation approach using runtime type information. After that, we'll look at some transformations we can do to improve other types, and then we'll focus on how we allow manual type overrides to improve the developer ergonomics. And finally, we'll have a quick look at compatibility dates.

First off, how we did types a few years ago. Like most run times, we had an npm package providing global types for our run time. Importantly, this package only included CloudFlare specific APIs, like HTML rewriter, and not web standards. There were quite a few problems with this approach. Firstly, these types were handwritten, making them error prone to update. Secondly, these types weren't typically updated by the team implementing the run time, making them slow to update with new APIs. On the right, we've got an example of a type error using a new API, even though that code should run fine in Rutgers. However, the biggest problem was with our reliance on libwebworker. This included APIs like message channel, which we didn't implement, meaning code type checked wouldn't run in our runtime. And workers at the time weren't fully spec compliant. We were also missing experimental APIs that we had implemented. So there are a few problems here. Now that we've seen all the problems, what should we do about them? So the workers runtime provides a run time type information system. This allows us to query types at run time, and was originally used for automated fuzz testing.

2. Encoding and Transforming Type Information

Short description:

Run time type information is encoded as cap and proto, which we use as a language and platform-independent binary format. It's basically a typed version of JSON. We can encode all runtime API types in C++ and do further processing in TypeScript. This allows us to use the TypeScript compiler API for rendering TypeScript. With a bit more work to convert cap and proto types into TypeScript, we have auto generated types. The types still aren't perfect, but all the information we need to fix these problems are already in the types.

Run time type information is encoded as cap and proto, which we use as a language and platform-independent binary format, kind of like protocol buffers if you've used those before. It's basically a typed version of JSON.

This is our cap and proto schema for type information. You can see that this kind of maps to TypeScript types. The really nice thing about cap and proto is that it can generate encoding and decoding code for you from your schema for many different languages. Importantly, this means that we don't have to implement all stages of the auto generation pipeline in the same language.

We can encode all runtime API types in C++ and do further processing in TypeScript. This allows us to use the TypeScript compiler API for rendering TypeScript. What we want to do is build the interfaces from run time type information. We'll try to build the interface we've just seen. We'll build from the bottom of the tree, so we'll start with the key parameter for the get method, then we'll build the get method's return type and the method itself, then we'll build the interface containing the get method, then we'll create a placeholder source file and printer so we can print out the interface to a string and log that to the console. If we run that, we get what we expected.

All that for three lines of TypeScript, this is a very verbose API, but with a bit more work to convert cap and proto types into TypeScript, we have auto generated types. This pretty much solves all of our problems from earlier. We've got exactly the APIs that implemented in the runtime with the minor spec differences. But the types still aren't perfect. For example, iterators don't have correctly typed values, we can't use any global functions or constants, and we don't have function overloads, so TypeScript can't narrow return types given arguments.

Luckily, all the information we need to fix these problems are already in the types. What we need to do is transform them into a form TypeScript recognizes. So we'll start with fixing iterators. This is what our types look like at the moment. We want to use TypeScript's built-in iterable iterator type instead, and the transition kind of looks something like that.

To fix globals, we need to extract service worker global scopes members into the global scope, and this will need to include superclasses too. So, again, we need to perform something like this. So how do we actually do this? Let's look at a simpler example. Say we want to replace all strings with numbers. We can write a TypeScript transformer for this that recursively visits all nodes. If we find a string token, we replace it with a number. Then we can use the TS transform API to apply this to an AST node. We start at the root KV namespace declaration, and we do a depth first search until we find a string.

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'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.
Full-stack & typesafe React (+Native) apps with tRPC.io
React Advanced Conference 2021React Advanced Conference 2021
6 min
Full-stack & typesafe React (+Native) apps with tRPC.io
Top Content
Alex introduces tRPC, a toolkit for making end-to-end type-safe APIs easily, with auto-completion of API endpoints and inferred data from backend to frontend. tRPC works the same way in React Native and can be adopted incrementally. The example showcases backend communication with a database using queries and validators, with types inferred to the frontend and data retrieval done using Prisma ORM.

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.
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. 
Frictionless Development With Unified Type System
JSNation 2024JSNation 2024
113 min
Frictionless Development With Unified Type System
Featured Workshop
Ejiro Asiuwhu
Ejiro Asiuwhu
Imagine developing where frontend and backend sing in harmony, types dance in perfect sync, and errors become a distant memory. That's the magic of TypeScript Nirvana!
Join me on a journey to unveil the secrets of unified type definitions, the key to unlocking frictionless development. We'll dive into:
- Shared language, shared love: Define types once, share them everywhere. Consistency becomes your BFF, errors your worst nightmare (one you'll rarely see).- Effortless coding: Ditch the manual grind of type checking. TypeScript's got your back, freeing you to focus on building awesomeness.- Maintainability magic: With crystal-clear types guiding your code, maintaining it becomes a walk in the park. More time innovating, less time debugging.- Security fortress: TypeScript's type system shields your app from common vulnerabilities, making it a fortress against security threats.