Type System React

Rate this content
Bookmark
Slides

TypeScript's type system is incredibly powerful. It can represent bizarrely complex interdependent JavaScript types and comes with a Turing-complete set of logical conditions. But this is a React conference, right? Let's implement a primitive React purely in the type system. For fun!

21 min
12 Dec, 2023

AI Generated Video Summary

This Talk is about implementing a limited subset of the type equivalent of React, specifically its JSX engine, in the TypeScript type system with no runtime code. The speaker demonstrates how to use TypeScript features like constrained types and template literal strings to infer and render JSX elements in the type system. They also show how to render headings and children using a utility called 'render component'. The Talk concludes with additional resources for learning TypeScript and related topics.

1. Introduction to Type System React

Short description:

Hello and welcome to Type System React with me, Josh Goldberg. I am a full-time open source maintainer in the TypeScript ecosystem. We're going to implement a limited subset of the type equivalent of React, just its JSX engine in the type system with no runtime code. Let's begin in TypeScript lang dot org slash play.

Hello and welcome to Type System React with me, Josh Goldberg. I am a full-time open source maintainer in the TypeScript ecosystem. I work on general projects that help you write TypeScript a little better, most notably TypeScript ESLint, the tool that lets you run standard JavaScript tools, such as ESLint and Prettier on TypeScript code.

I'm also the author of the learning TypeScript book through O'Reilly, so I like talking about TypeScript. Everything we're going to chat about today is on GitHub and open source under Type System React, a repo in my Josh Goldberg user, but I want to note that this is not normal TypeScript. You don't need to follow along precisely and get everything fully to be a TypeScript dev or to work proficiently in TypeScript. This is all shenanigans today, and while the concepts I'm going to show are actually really useful for working in the type system if you do it a lot, it's not stuff that you should be using day-to-day. It's all silly stuff, all the weird shenanigans.

Because what we're going to do is implement a very limited subset of the type equivalent of React, really just it's JSX engine in the type system with no runtime code. We're going to make a type, let's say a component registry. We're going to make a helper type render that takes in a string and gives back the JSX results, the rendered results, and we're going to print that out to the developer tooling stuff that's running TypeScript for us. So very much not practical. You would never satisfy any user needs with this, but I think it's a cute way to explore the type system.

So let's begin. You can find all the code I'm going to send my live code under the repo under source slash fun, but I'm going to be working in TypeScript lang dot org slash play, which is a really nice playground available on the TypeScript website. You can type in TypeScript code on the left and get back JavaScript code or any errors, declaration files on the right. Now on the left, I have just some standard TypeScript code. I have a type component registry and a console log, and we can see that the type system representation just includes the type and the JS representation just includes the JavaScript. But I mentioned that today is purely in the type system. So I'm just going to go ahead and remove our console log. No JavaScript just types. But that brings up the question of how are we going to print things. So I'm going to make this little temporary type print me here. I'm going to say I want to print component registry. And there's actually a nice little TypeScript playground and other TypeScript editors feature called to slash assertions. You can get an extension of VS Code to do this. But if you write a comment that has this little caret and a question mark, it will ask it to print to the screen what you would have gotten if you were to hover your mouse there. So here we got type print me as the component registry type. And printed out, we got the stringified version of that. Emoji is sparkling heart.

2. Exploring Tag Rendering and JSX in TypeScript

Short description:

I'm going to switch to sparkles and heading is H1 with children. I want to be able to get a tag name and render out the contents under that tag. TypeScript has a feature called a constrained type to ensure we're only passing in one of the actual keys. I'm going to extract that out to a component type so that whenever I say component, what I really mean is one of the keys of the registry. I want to be able to have JSX and self-closing tags, which is not supported currently.

I'm actually going to switch to sparkles, a little less glaring, and heading is H1 with children. Hooray. Printing in the type Printing in the type system.

But I need to do more than that. I want to be able to, let's say, get a particular tag name and render out the contents under that tag. And you can do that in TypeScript with this index signature lookup, this little array type. Here we're saying give me under component registry the type under the emoji property name, which in this case, yes is sparkling hearts, pardon me, sparkles. If we were to switch that to heading, we'd get H1 children slash H1. If we were to switch that to, I don't know, ASDF WAT, some gibberish, we'd get Red Squiggly's property ASDF WAT does not exist in type, component registry.

Cool. And that little constraint there, the fact that it needs to be one of the actual keys of the type is useful because I want to write a render type which takes in a type parameter and gives me back component registry of that type parameter, making a kind of dynamic version of what I'm doing here. If I were to say want to render emoji, this fun fact actually works. This is what's called a generic type or type with a type parameter. It's kind of like a function in the type system. We take in a tag, say emoji, the string, and then we do something. We create a new type with that tag. Here we're making component registry of tag as a result, but we're getting the complaint type tag cannot be used to index type component registry. In fact, if we switch to the errors tab here, we can see that. Well, that makes sense because what if I passed in asdf? We need some way of making sure we're only ever passing in one of the actual keys of this type. And TypeScript has a feature for that, it's called a constrained type. With the extends keyword, we can extend key of component registry. Voila, no more red squigglies. Print me is happily the sparkling emoji, and here we're saying tag extends or must be one of the keys of component registry. I'm actually going to extract that out to a component type here so that whenever I say component, what I really mean is one of the keys of the registry. If we were to switch this to heading, yep, it renders the heading nicely. Rendering, it's a start. But I want to be able to do more than just take in a tag name and render under the tag. I want to be able to have JSX. I want my little self-closing tags. I want to be able to do something like emojis self-closing, which right now is not supported.

3. Type System JSX Rendering

Short description:

In order to grab something out of the provided type, we use a conditional inferred type. We can reach into the provided type, grab the tag, and return it. We can also use template literal strings in the type system to infer the tag. By using the extends keyword, we ensure that the tag matches the component registry. This allows us to render a JSX element in the type system.

In order to do that, I need to be able to reach into the provided type and grab something out. In this case, the emoji substring. And the the way you do that is with something called a conditional inferred type.

I'm going to actually just quickly type that up given a render, which maybe, maybe we're just going to start with objects. If the provided object matches some template, if raw extends, coincidentally the same extends keyword, text, let's call this string, then yay, otherwise, no. Here we see that okay, this conditional type is in fact saying that raw extends this object type text string. Yay, no. That's a conditional type.

Now we can add in this infer tag. So let's call this tag actually. Tag. Aha! Now, we are reaching into the provided type raw, grabbing out the tag, and then returning it kind of like again, a function of the type system. But we're able to do a little bit of logic almost here. We're checking whether this condition is met. And this is a ternary just like you would have a question mark and colon in the runtime space. But I mentioned earlier, I wanted not object shapes, but I wanted string shapes. So I want to be able to do this. Self-closing tag. And you can do that, actually. You can have template literal strings the type system, and you can infer within them. You can say, doesn't match this pattern. Infer tag. If so, give me back the tag. Emoji. But that's just the tag. So what I really want to do is get component registry of tag. And now we get that same complaint from before. Type tag cannot be used to index component registry, which means I again have to use the extends keyword to say, only match if the tag extends components. And voila. We are able to render a JSX element in the type system.

4. Type System JSX Rendering (Part 2)

Short description:

To recap, we check if the raw extends a string template. If so, we return the contents under the registry of that tag. We can use template literal strings to add before and after the tag. We can recursively render multiple tags. Instead of rendering invalid, we render the original input. Recursive descendant rendering allows for more than just self-closing tags.

To recap before we move on and get more fancy, is we are checking, did this raw, and I'm just going to go ahead and say it should always be a string. Does this raw extend a string template like the following? Starts, some tag that's a component. Close. If so, give me back the contents under the registry of that tag. Otherwise, I'm going to call this invalid to make it clear.

Yay, we are halfway there. But I want more. I want to be able to, let's say, print hello world before the emoji, which right now isn't supported, because this does not strictly match the self-closing emoji tag. Fortunately, I can use these template literal strings in my results. I can add in another infer before, and print before, and that works. And I can do infer after, which in this case is an empty string. Let's say we want an exclamation mark there or something. Don't need that paint anymore. Let's scroll down a bit. It's beautiful. Hello world emoji. That works. But what happens if we have multiple emojis? Let's say I want to render three sparkles. Well, it doesn't right now, because when we infer the after, we're directly plopping it back as a string. We need to recursively render. We need to take whatever's after the component, registry into the tag, and give it back. We need to rerun the render on it, recursively rendering until there's nothing more, which actually does work. So that's awesome. But then we get invalid at the end, which actually I think makes sense, because once we're done rendering the last self-closing tag, what we have left is the empty string, which does not match this template. So instead of rendering invalid, we can render whatever we were given to begin with. There it is. Recursive descendant rendering.

But I want more. Always more. I want not just self-closing tags.

5. Rendering Headings and Children

Short description:

I want a heading. If raw doesn't extend from the self-closing template, but it does match a template for children slash tag, then we render the heading with children. I write a utility called render component to render the children somewhere along ComponentRegistry. It works because raw matches the template that contains children.

I want a heading. I want heading, hello world. Let's stop with these emojis quite so much. Let's do heading like this. There we go. Yeah, this isn't working. This is not detecting. So I'm going to need to add another condition.

Which, fun fact, you are allowed to do. I'm going to have to say if raw doesn't extend from the self-closing template, well, what if it extends from a different template? In this case, for children slash tag. So it's the same as before. We're adding another case where if it didn't match the self-closing template, but it does match a template for, let's see here, start tag, some inferred children, and end tag, then we do render, and it works. We see a heading rendered right here. Heading, and then we even still recurse onto the after. So we get the second, the sparkle. It's awesome, but I want children, which means I'm going to actually go ahead and write a utility here, because I want to render the children somewhere along ComponentRegistry.

So I'm going to write type render component, which takes in tag extends components, again, kind of like a function in the type system. And then I'm going to also take in children extends string. And I'm going to check, does components registry of tag extend some template that has before this indicator that I want children, then infer after if it does, then the result will be before the children and after. Otherwise, we're going to directly return component registry of tag, like nothing ever happened. And I'm going to use that here. Render components of tag. Ooh, and of children, and there we go. And voila, it works. Heading, which becomes the H1 and it renders the Hello World. If I were to ya-ya-ya, ya-ya-ya, it works. And it works because raw matches to this with children template, which means we then run to render component and component registry of, in this case, heading, does in fact match the template that contains children. So we effectively string replace the children with children. So that makes me happy. But a little bit more work, we're seeing that the children includes the raw emoji tag, but I actually wanted to render that.

6. Rendering Component and Recap

Short description:

In the render component, I'm going to swap to render children instead of directly returning component registry. I'll use the same render component generic type, defaulting children to the empty string. This is a working implementation of a limited subset of React JSX rendering engine in the type system. The render function checks if the text matches specific templates and renders accordingly.

So in the render component, I'm going to swap. Instead of directly returning component registry, I'm going to do render children, and that works. Hello World sparkles. Ah, now I suppose we could always render children in case the components refer to each other, but that's a little out of scope for this 20-minute talk.

So that's cool. And that's actually working pretty well. I'm just going to do a little bit of code cleanup. I'd like to use the same render component generic type here, but in the self-closing tag case it's an empty string for children, which means I can call onto a typed code feature default types to say in my render component if I don't have any children, just default them to the empty string. Making this code here I arguably think a little cleaner.

And there you have it folks, a working implementation of a very limited subset of React JSX rendering engine in the type system. Let's recap from the top before we finish up. I've declared a component registry type here, which is the concept of an object that has two properties. One emoji has the sparkle string emoji as its value. Not just any old string, but specifically that string. And also heading, which is h1, this indicator that we have children, slash h1. I then declared the utility type components here, which is any of the keys of component registry, practically speaking of emoji and heading. I then declare this render component type, which is a generic type. It takes in type parameters and returns a resultant type based on that. It takes in one of the components, so a tag. And then children, which is a string that defaults to the empty string. It checks. Does a component value under that tag extend from this template? So text before, the children indicator, text after. If it does extend from that template, then you render, or you return a result of before, the rendered children, and after, otherwise give back the component itself. That's used in our main, our driver, our worker type, render, which takes in some raw text and it checks two conditions. If the text is this template, any string before, the component tag inside a self-closing little area, and after, then we result in the before text, the render of the component, render of the after. Otherwise, if it's a component with a slightly different template, if it's before the lesson sign, the component itself with some children and then the component again with some after. Similarly, we render before. Render component, tag children. Render after. If the raw text didn't match either of those two templates, we return it directly.

7. Wrapping Up and Additional Resources

Short description:

And at the very end, print me is the result. I feel very cool and strong doing that. It brings me a lot of joy to mess with TypeScript. This is not something you need to use on a day-to-day TypeScript basis, it's just some cool stuff to explore. If you want to learn more, typescriptblind.org and theplaygrounds/play are fantastic. I also have a book, Learning TypeScript, and recommend definitelytyped and type challenges as resources. Anything you can send my way would help me work for all of y'all. You can find me online as JoshuakGoldberg.

And at the very end, print me is the result, where we take in this text, we recurse a couple free times, and we get back our string results. Yay. I feel very cool and strong doing that. And this makes me happy. It brings me a lot of joy to mess with TypeScript in this way. But I totally understand if this is not for you, if you've never played with TypeScript before or done deep things in the type system, that's totally fine.

Again, this is not something you need to use on a day-to-day TypeScript basis, it's just some cool stuff I think that is fun to explore with some of the type system techniques and foundations. If you want to get started with TypeScript, I do have most of the concepts you need for this in a different folder in the same repo source slash foundations.

So that was fun. Let's wrap up. Let's talk about a little bit of other stuff for now. If you want to learn more, typescriptblind.org and theplaygrounds slash play are fantastic. They're open source online. I highly recommend. I also mentioned I have a book, Learning TypeScript, which you can absolutely try out. Its website has a lot of free open source articles and projects to help you flesh out your TypeScript understanding. And if books aren't for you, or if you just want more or another resource, I really like mattpocockstotaltypescript.com. If you're wondering, this is all cool stuff, what on earth am I going to do with it? Well, a couple places you can go after this, definitelytyped is one of the largest public open source repositories in the world.

It is the place that all third party types, so packages that don't describe how they look to TypeScripts, you can describe how they look in this repo exist. So if you want to say, look at React's type, because React has definitely typed types, you can go to definitelytyped, types, react, index DTS, and see a whole bunch of syntax that actually uses a lot of the features we played with today. So if we ever have a problem with a third party type, or there's a package you use that doesn't have type information, definitely typed is a place you can go to make progress on that, to make it better for everyone. Secondly, type challenges is a great repository. Also, they've got a really cute little homepage, type challenge that links to the GitHub. It's got a whole bunch of starting small, getting much more complex type challenges to flex the concepts we showed today. Type system is incredibly powerful and could actually model not just React but TypeScript itself. People have implemented TypeScript in the TypeScript type system. If you want to be one of those ridiculous people, this is a way to get yourself there. Or you can just use the easy and medium challenges to flesh out your basic TypeScript and foundational TypeScript type system features. Everything we've talked about today is, at the very least, built towards my book Learning TypeScript. Highly recommended. I think it's pretty good. Also, because I'm a full-time open source maintainer, anything you can send my way, in terms of love, appreciation, money, issues filed, pull requests sent will help me work for all of y'all. Similarly, TypeScript VS Lint is an independent project. We're not associated with any one company. So, anything you can do to help us to file bugs, to send code and send us money would really be appreciated, to help us continue to make TypeScript better for everyone. With all that being said, I had a great time with this. I hope you enjoyed it. You can find me online as JoshuakGoldberg on most sites, including by joshuakgoldberg.com.

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

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.
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.
React Day Berlin 2023React Day Berlin 2023
21 min
React's Most Useful Types
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.
React Advanced Conference 2021React Advanced Conference 2021
6 min
Full-stack & typesafe React (+Native) apps with tRPC.io
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.
TypeScript Congress 2022TypeScript Congress 2022
10 min
How to properly handle URL slug changes in Next.js
If you're using a headless CMS for storing content, you also work with URL slugs, the last parts of any URL. The problem is, content editors are able to freely change the slugs which can cause 404 errors, lost page ranks, broken links, and in the end confused visitors on your site. In this talk, I will present a solution for keeping a history of URL slugs in the CMS and explain how to implement a proper redirect mechanism (using TypeScript!) for dynamically generated pages on a Next.js website.

Add to the talk notes: https://github.com/ondrabus/kontent-boilerplate-next-js-ts-congress-2022 

Workshops on related topic

React Advanced Conference 2021React Advanced Conference 2021
174 min
React, TypeScript, and TDD
Featured WorkshopFree
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.
React Advanced Conference 2022React Advanced Conference 2022
148 min
Best Practices and Advanced TypeScript Tips for React Developers
Featured Workshop
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.
TypeScript Congress 2023TypeScript Congress 2023
131 min
Practice TypeScript Techniques Building React Server Components App
Workshop
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.
TypeScript Congress 2022TypeScript Congress 2022
116 min
Advanced TypeScript types for fun and reliability
Workshop
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
TestJS Summit 2023TestJS Summit 2023
78 min
Mastering Node.js Test Runner
Workshop
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.
Node Congress 2021Node Congress 2021
245 min
Building Serverless Applications on AWS with TypeScript
Workshop
This workshop teaches you the basics of serverless application development with TypeScript. We'll start with a simple Lambda function, set up the project and the infrastructure-as-a-code (AWS CDK), and learn how to organize, test, and debug a more complex serverless application.
Table of contents:        - How to set up a serverless project with TypeScript and CDK        - How to write a testable Lambda function with hexagonal architecture        - How to connect a function to a DynamoDB table        - How to create a serverless API        - How to debug and test a serverless function        - How to organize and grow a serverless application


Materials referred to in the workshop:
https://excalidraw.com/#room=57b84e0df9bdb7ea5675,HYgVepLIpfxrK4EQNclQ9w
DynamoDB blog Alex DeBrie: https://www.dynamodbguide.com/
Excellent book for the DynamoDB: https://www.dynamodbbook.com/
https://slobodan.me/workshops/nodecongress/prerequisites.html