ArkType: Bringing TypeScript to Runtime

Rate this content
Bookmark

ArkType is a new runtime validator for TypeScript and the first library with the goal of making type syntax available 1:1 in JS with no compilation step.

It uses a carefully optimized static parser so that with each character you type, you'll see a list of completions, a clear ParseError, or your inferred type. At runtime, a simple definition like "string|number[]" will be transformed into a TypeNode that can be used to validate or transform inputs, compared to other TypeNodes, or combined with other definitions to form new TypeNodes.

This talk will cover the process of building ArkType, with a focus on the type-level parser and runtime type system, and demo some of the most exciting features like scopes, index signatures and generics.

David Blass
David Blass
21 min
21 Sep, 2023

Comments

Sign in or register to post your comment.

Video Summary and Transcription

This Talk discusses the concept of runtime validation in TypeScript and how it bridges the gap between TypeScript's expressiveness and runtime capabilities. The speaker explains the evolution of top-down parsing and the shift-reduced parser that made runtime validation possible. The benefits of runtime validation in terms of flexibility, scalability, and efficiency are highlighted. The integration of validation and the type system is emphasized, along with the enhanced validation capabilities and new features offered by the Archetype framework.

1. Introduction to Runtime Validation in TypeScript

Short description:

Hey, everyone, my name's David. I'm here to talk about runtime validation in TypeScript. There are great solutions out there, but there's a gap between TypeScript's expressiveness and runtime capabilities. I asked myself how we could express a TypeScript type for runtime use. The answer is simple: leverage the same structures as JavaScript. With some adjustments, we can achieve a one-to-one parallel between TypeScript and runtime validation.

Hey, everyone, my name's David. I'm very lucky to be here today and have the chance to talk to you about one of my absolute favorite topics in the TypeScript ecosystem, which there are many. But as many of you may know, one of them is perhaps the nearest and dearest to my heart, which is runtime validation. So this is something that's been discussed very frequently by the community in the past and solved many times by some fantastic engineers. So there are some great solutions to this out there.

But when I was looking at this problem, I couldn't help but feel there was this gap between the expressiveness and power of TypeScript and its type system and its syntax versus what was available at runtime through some combination of builder methods or various things like that. So essentially this is a couple years ago I asked myself this very dangerous question of what is the closest we could get to expressing a TypeScript type like this in a way that we can use at runtime. So remarkably the answer is pretty simple. And I don't think there's actually as much ambiguity as there is when you're answering most design problems like this. So luckily TypeScript leveraged a lot of the same structures for its object literals, tuple literals, etc. as our built in to JavaScript.

So we can do the same thing. We can say name as a string. Sure. OK. So we have to embed this. We got a device. We got a nested object here. Platform. So this will be a little tricky because they're already in a string. So probably have to do some kind of nested quotes or something like that. So that we know we're still in a string literal since Android and iOS aren't keywords. And then just a couple ways you could go about this one. But let's just go with this. So this is the closest I think you could basically get to a one-to-one here, if you compare these two things, look at this. You know, we don't have an as const here, but essentially these two have a very strong parallel, right. So the question is, is this structure something that we could theoretically use for runtime validation in a way that captures the essence of what makes TypeScript index so powerful and extends that for some of the core needs of a runtime validator.

All right, so fast forward, give or take a few months. Basically what I'm facing here is we need some way to take that original structure that looks just like TypeScript type but infer back out the original TypeScript type without all that runtime embedded syntax that's designed to fit within JavaScript. So essentially, after some iteration, I came up with this initial solution.

2. Evolution of Top-Down Parsing

Short description:

You can see that I called it parse type, which eventually evolved into arc type. It was the beginning of my iterate on types, type iterate. It had some inherent limitations. I added cyclic inference capabilities. I added function parsing for some reason. This top-down approach had little control over precedence and other issues. Eventually, I realized it's not going to work for a fundamentally scalable solution.

You can see that I called it parse type, which eventually, as you can probably guess, evolved into arc type. And it was just a simple process of a couple of years and some iteration. So as you can imagine, this is the beginning of my iterate on types, type iterate. And it has, kind of, been a theme since then. But there's a few intermediate stages and you'll be able to see a little bit about how some of this evolved.

So this is my initial stab at things. It's got some fairly complex types in it. It's this top down parser approach doing a lot of pattern matching. It's a pretty... I'll say familiar. I mean, this is a little crazy stuff still. But in terms of what had been done within TypeScript in the past for parsing, it is kind of this, like, hey, does this match this template expression? If it does, then infer this part of the syntax. Otherwise, do the same thing. So somewhat straightforward. But I would find that it had some kind of inherent limitations.

So got some nice error messages. Impressively, one of the first things I added was this, kind of, cyclic inference capabilities. So it's able to do that. So that's cool. I added function parsing for some reason, which is useless for run time validation. So I think I just thought it was cool or something. I'm not sure why that was there. This precedence issue would kind of continue to be a thorn in my side. Because I had very little control with this top-down method in terms of ensuring, for example, that the array operator had higher precedence than the union operator. And that was really the most straightforward manifestation of this issue. As I went on, I would discover others, like trying to represent string literals like this, yes or no. Well, you need to make sure that it's not interpreted as the string literal containing that union operator. So this top-down approach, you know, I'm going to continue and try to work around it for a while. But eventually I'm just going to figure out, you know, it's just not going to work. This case was the specific one that made me realize, okay, there's no way that I'm actually going to be able to use this approach at all if I want a fundamentally scalable solution.

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.
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.
Faster TypeScript builds with --isolatedDeclarations
TypeScript Congress 2023TypeScript Congress 2023
24 min
Faster TypeScript builds with --isolatedDeclarations
Top Content
Type-checking a TypeScript codebase can be slow, especially for monorepos containing lots of projects that each need to use the type checker to generate type declaration files. In this talk, we introduce — for the very first time — a new TypeScript feature we are working on called “Isolated Declarations” that allows DTS files to be generated without using the type checker at all! This opens the door to faster declaration generation in TypeScript itself, as well as in external tools written in other languages such as ESBuild and swc. You'll see how to use this new option, and maybe (just maybe) you’ll be convinced about the benefits of explicit return types! Most importantly, we will show how Isolated Declarations enables parallel builds to spread work across your CPU cores to significantly improve the build speed of your TypeScript projects.
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
Why are we devs so obsessed with decoupling things that are coupled nature? tRPC is a library that replaces the need for GraphQL or REST for internal APIs. When using it, you simply write backend functions whose input and output shapes are instantly inferred in your frontend without any code generation; making writing API schemas a thing of the past. It's lightweight, not tied to React, HTTP-cacheable, and can be incrementally adopted. In this talk, I'll give a glimpse of the DX you can get from tRPC and how (and why) to get started.

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.