7 TypeScript Patterns You Should Be Using

Spanish audio is available in the player settings
Rate this content
Bookmark

In this talk, we will be going over a number of common useful and best-practice-proven TypeScript patterns to use in React 18. This includes how to correctly type component properties, children and return types, using React's built-in types, typing contexts, and the usual enum rant (but constructively).

19 min
06 Jun, 2023

Video Summary and Transcription

This Talk introduces 7 essential TypeScript patterns for React development, including children, spreading props, either-or, generic components, and context. The speaker demonstrates various implementations and provides examples using a fictional dog grooming salon application. Other interesting ideas include using omit and make required types, creating components with either-or interfaces, and using generics, memorization, and context in React. The speaker also introduces the Recontextual library for context management.

Available in Español

1. Introduction to TypeScript Patterns in React

Short description:

Did you know that despite the fact that around 80% of React developers are using TypeScript, most of the courses, books, and supporting materials for learning React are almost exclusively in JavaScript? Today, I'm here to share with you 7 essential TypeScript patterns that you can start using right away to make your React development safer, more efficient, and more enjoyable than ever before. My name is Morten and I'm a React and TypeScript enthusiast. I'm the author of 2 books on React. Follow me on LinkedIn and subscribe to my newsletter at mortenbaklund.com for more tips and tricks.

Did you know that despite the fact that around 80% of React developers are using TypeScript, most of the courses, books, and supporting materials for learning React are almost exclusively in JavaScript? This has left many developers struggling to navigate the complex role of TypeScript in React development.

Today, I'm here to change all that. I want to share with you 7 essential TypeScript patterns that you can start using right away to make your React development safer, more efficient, and more enjoyable than ever before. My name is Morten and I really like dogs. I'm here as both a React and TypeScript enthusiast. I'm the author of 2 books on React. First React Quickly, a primer on React fundamentals. It's at the printers pretty much right now and will be out in print this month. Secondly, Job Ready React. It builds on the first book. It covers the React ecosystems and more complex React patterns. It's in the works, about 80% done, will be out in the fall sometime. You can get the books from the two links above or just by Googling the titles really. Besides that, I also run workshops and I'm working on a new course platform that I think will be quite innovative. You can read about that at codingheaven.deb. Finally, follow me on LinkedIn and please do subscribe to my newsletter at mortenbaklund.com for lots more tips and tricks.

2. Introduction to React Component Patterns

Short description:

In this part, we'll cover seven essential TypeScript patterns for React development. These patterns include children, spreading props, either-or, generic components, and context. We'll explore different variations and implementations, even sacrificing proper React coding to illustrate key points. Additionally, we'll work with an application called Waxville, a fictional dog grooming salon, to demonstrate the patterns. The application is available on GitHub and waxville.org, but please note that it only stores data in memory and is solely for illustrative purposes.

All right, back to the topic. The title here is a bit hyperbolic. These patterns tend to blend a bit into each other, but the overall plan is as follows. We'll introduce what we want to achieve by looking at the final application. Then we'll look at the API from the parent component perspective and then we'll see how we can implement that inside a component. We'll probably look at a few different variations and see which one is the best one.

The examples are not always great code design because some of these examples have been reduced a bit in complexity to make them simple and instructive. The patterns are still fully valid, but they only appear in more complex code. So I've sometimes sacrificed proper React coding a bit to illustrate some points.

These are the seven patterns we'll cover. Children, spreading props, either-or, generic components, and context. You might now be thinking, wait, was that seven or was that only five? So let's expand the list a bit because we can do this in a few different ways. So either-or, we can do that with unions or discriminated unions. Those are slightly different patterns that are definitely both valid. And for context, there's two different situations that have definitely different complexity. We have simple context and we have selectable context. Those are very different, and we'll see how we can implement both of them.

In this talk, I'll be working on an application called Waxville. It's a fictional dog grooming salon that I've created just for this talk. You can see the repo here on GitHub, and you can see the website live at waxville.org. You can go see that right now. This is just a quick demo that you can see that you can log in. It doesn't actually matter what you type. When you press the button, you log in, and then there's a schedule with the daily appointments, and there's a CRUD interface for employees, customers, and services. Be aware, this is a very dumb website. It only stores the data in memory. So once you reload the website, everything you've done is gone. So this is to not make sure that anyone messes with it, but also it's enough to illustrate all the points we're going to make. This is not about data APIs. This is just about typing components.

3. Children Pattern in React

Short description:

The first pattern we'll discuss is children. It's a special property that needs to be typed correctly to allow different types of child content. We can use the props with children interface from the react package to ensure correct typing. This approach is more transparent and eliminates the need for custom interfaces when there are no additional props. We can also easily handle other properties by creating an interface for non-children props.

So the first pattern we're going to discuss is children. Children is a special property that you probably all know, and has to be typed correctly to allow the node to contain all the different possible types of child content. An example would be our auth provider that we have at the root of our application. We can type this using a custom interface, and we just type the children property as react-node from the react package. This type includes all the correct possibilities, including string, numbers, Booleans, elements, lists, etc.

However, I think a better and more transparent approach is to use the props with children interface from the react package instead. We don't need to have our own interface at all when we don't have any props. We just use this interface as is. It makes it more clear that we've correctly typed this children property. If our component takes other properties, we can easily deal with that too. Here we have the menu with menu items. A menu item takes a child attribute, but also takes a to property, which is the page it links to. We can implement that with Props with Children, where we just create an interface for the non-children properties, and we pass that as a type argument. This looks really nice.

4. Spreading Props in React

Short description:

Next, let's discuss spreading props, also known as mirroring the props of another component. We can achieve this by specifying an interface that mirrors all the properties of a normal button while extending it with custom ones. There are different approaches for achieving this, such as using the button.html.attributes interface or going through the JSX namespace. However, both approaches have drawbacks, such as awkward typing or including the ref property. To overcome these issues, I prefer using components without ref, which can be extended and does not include ref. This approach allows us to extract props for any component, including custom ones.

Next up, spreading props. This is also sometimes referred to as mirroring the props of another component. A very simple example here is a button. In the Custom Edit form, we have two buttons at the bottom, cancel and save. They're slightly different, but they're implemented with the same component. We can see them here in the Edit form, where the buttons take some default properties that normal buttons do, like type, onClick, and children, but also some custom ones, like outline and icon.

What we want to achieve is to specify an interface that mirrors all the properties of a normal button, but extends it with a few custom ones. One fairly obvious way is to use the button.html.attributes interface from React like this. It however has the drawback of requiring an additional interface for the event handler targets, where we need HTMLButtonElement from the DOM. It's a bit awkward to type button.html and then HTMLButton, but it works and is fully functional. Because of the awkwardness, it's not that used, this approach.

A more common choice is to go through the JSX namespace and access the intrinsic elements property. It addresses all the types for all the intrinsic elements. This has another weird drawback though. You cannot directly extend it. If you try to extend this with an interface, you get a weird TypeScript parsing error. The TypeScript grammar simply doesn't allow extending a bracket index interface like this. We can save it in a type and extend that. But we have to go through that extra type. Both of the above also have an additional drawback though. They both include ref because that's a valid property that you can pass to a component, but it's never a valid property to receive inside a component in the props object. So this would be valid TypeScript, but it doesn't really make any sense. That's not how we receive a ref. For those reasons, I prefer to use components without ref.

Component props without ref. It requires a specific element name as a type argument. And it can be extended just fine and it does not include ref. Which is pretty obvious from the name of it. This interface can actually be used to extract props of any component, including custom ones, but I use it mostly for intrinsic HTML elements. Sometimes we don't want to allow the same elements of the same properties for a built-in element.

5. TypeScript Patterns: Omit and Make Required

Short description:

To achieve a nice display model for a number input, we use the omit-typescript type and change the type of the value property. We can narrow the type without omitting it from the parent interface. For the Form component, we use the Make Required utility type to remove the optional part of the type and ensure the unsubmit function is required.

For example, for this number input that you can see in action here. It has a nice display model where the number is formatted differently on blur. To do this, we can't allow users of the component to specify type or pattern as that would circumvent the purpose. We implement this using the omit-typescript type. Further trick here is that we actually change the type of the value property. On a regular input element, value is an optional property that allows numbers, strings and undefined. But on our component, it's a required property that only allows numbers. We can do that without using omit. We don't have to omit it from the parent interface because we're narrowing the type. If you want us to change the type to something that was not included in the original, for example, a function, we'd have to omit it from the original before changing it. Narrowing is allowed when extending, but not changing. We also use this same idea to only remove the optional part of a type. For example, in our Form component, we want to require the unsubmit function. We cannot have that as optional. We want to make sure that everyone who uses this component always supply an unsubmit function. But the type of this one is a bit complex. We can use the original type, but then we have to index the original in this quite weird way. It's a bit repetitive, especially if we had more than one property we wanted to do in this way. A better way is to create a small utility type called Make Required, where we can use a type modifier to remove the optional part of the type by using this minus question mark syntax. It makes for a much cleaner interface and we now only have to specify the new types that are not on the original.

6. Components with Either-or Interfaces

Short description:

Next, we'll create components that require attributes to conform to either a link action or a click action. We'll use TypeScript's narrowing to determine the type of action based on the properties present in the value. Additionally, we'll explore discriminated unions and how they can be used to create components that can be either single select or multi-select, with corresponding callbacks that accept either single elements or arrays of elements. We'll also discuss the benefits of using union string types instead of enums for cases with more than two choices.

Next up we'll create components that require attributes to conform to exactly one of several interfaces in an either-or situation. In our table example, we have an ability to add action buttons as you can see here. These two buttons are slightly different though. One of them is a link, the other is a button with a callback. In the serviceList component, we can see here that we specify an action label always, but we either specify a link property or an onClick callback, but we cannot specify both, that would be invalid. We want to make sure to type this correctly inside the table implementation.

Here we see that action is a union type of link action or click action and our table then accepts an optional list of actions. Using this inside the component is a bit complex though. We have to utilize TypeScript's narrowing and the cleanest way to do that is to check if a given property exists in the value. If the action object contains a link property, then it's probably a link action, and even TypeScript knows that, so it knows the properties. If it doesn't contain a link property, it must be a click action, so it contains an onClick function, and TypeScript knows that as well. But the property check is a bit ugly. We can move it to a type guard and we do the same thing, and it looks better, but it's still a bit complex. What if we instead had a property on the different interfaces in the union that could directly discriminate between which specific union member we were working with? Well, that's a discriminated union.

We have another example here in our Select component. Our Select component can either be a single select or a multi-select, as you can see here, two different selects in the same form. The difference is that the value for a single select is a single element, but for multi-select it's an array of elements. And for the callback, we can also either get a single element back or we get multiple elements back in the callback. You can see here how if we add a manual callback to these two components it knows directly if it received a single string or if it receives a list of strings. We can implement that with two interfaces that share a property that directly tells us which case we have. That's of course the multiple property. We can directly use that property inside the implementation to correctly invoke the callback with the proper arguments. And TypeScript correctly knows that the callback accepts these correct arguments. In this example we only had two choices, so it could be done with a Boolean. If you have more than two, the easiest way is to implement this with a union string type. You don't need an enum. There's nothing an enum could give you that a union string type couldn't do just as well. You would only just create unnecessary code, which enums do. So stick with a union string type and you'll be good. However this select, it only accepted strings and then returned strings back.

7. Generics, Memorization, and Context in React

Short description:

To put in an arbitrary element and receive it back in a callback, we use generics. The table displays different columns in different lists, implemented with a generic type. However, when memorizing components, the specific type of argument is lost. We can fix this by changing the type of the memorized component or the global type for the memo function. Context is a more complex topic, where we use React's built-in context to serve our auth provider in the login component.

What if we wanted to put in an arbitrary element and receive that same element back in a callback? To do that we need to use generics. Let's take a closer look at our table from before. We can see the table displays different columns in the different lists. We do that with a generic type. You can also see here that in the on click callback for an action it knows exactly which properties exist on the particular element and this directly maps back to the input rows for that same table. This is implemented with a generic type.

We restrict the generic type to extend a record with an ID and we otherwise just use the generic type as we'd use any specific type. There's one small caveat to this in React though. If we memorise the component and go back to where we used the link action, it suddenly forgot what specific type of argument it received. Memorise simply removes any generic types. So this now is only typed as a record with an ID. It doesn't know about any of the other properties. That's how a memo function is typed in React. I think it's a bit broken and it should be fixed. But for now we can fix that in one of two ways. If this is just a one-off component we have, we can fix it by simply changing the type of the memorised component to be the same as the type of the component. It's very simple. If we have to do this at scale for multiple components, we can instead change the global type for the memo function inside React. Yes, we can do that. We just specify that the memo just returns whatever it receives. ForwardRef has the exact same issue. And that might also come up in your code. And it's a bit trickier to type correctly, but you can still do that in both ways.

Let's move on to a more complex topic. Context. First we have a simple context. It's our auth provider. We'll use React's built-in context to serve it. It is used in the login component. So when we press the login button, we invoke the login function from the context.

8. Creating Context in React

Short description:

When creating a context in React, allowing the context to be null can make the process easier. However, passing null as the value in the provider can break the consumers. If null is not allowed, creating the context becomes more complex. Typing out the context with multiple properties can be tedious.

And that changes some flag somewhere saying that we are now logged in. In the root component, we send the user to a different page depending on the logged in status. In the login component, we invoke login from this context and that is done on form submission. We create this context with an interface and the built-in create context. Here we additionally allow the context to be null. Just to be able to pass a null into create context. This makes it a lot easier to create the context. We have a custom hook for accessing the context which fills out null. So we know that's not going to happen and it always just returns the context value. In the auth provider, we pass in a value with a proper structure. But as you can see here, we could actually pass in null for the value in the provider. It will break the consumers as we throw on null, but the type system actually allows it. If we did not allow null, we will have to create the compact context in a more complex manner for no real purpose. Here we only have two properties, but if we had more properties, it would be a really long, really annoying contexts to type out.

9. Using Selectable Context and Recontextual Library

Short description:

Sometimes people use partial instead, but it leads to the same problems. A better approach is to use a selectable context. There's a great library called useContextSelector that allows us to do just that. We can now pass a selector function. When we select from our context, we have this overloaded function. It's not pretty. It's a bit complex, but it works. For that very reason, I've created a small library called Recontextual which does exactly this. It wraps useContextSelector and simplifies the API. Let's see how we use that in ScheduleProvider.

Sometimes people use partial instead, but it leads to the same problems. For instance, in the login component, we will have to check if the login function existed before we could invoke it, because it's now an optional property and not a required property.

A simple context like this is not useful at scale. If any property inside the context changes, every consumer re-renders. In our example from before, the login component re-renders when we log in, because it is logged in property of the context changes, even though we don't use that property in the login component at all.

A better approach is to use a selectable context. There's a great library called useContextSelector that allows us to do just that. Let's look at the underlying API provider that handles all the primary data for the CRUD application. This API allows us to edit, add, and delete services, and handles updating the state. But we don't want context consumers that aren't using NGATE services to re-render just because we add a new service.

We can now pass a selector function. In the schedule, we select a single property from the API provider, the employees, so we can display them all. But more often, we actually select multiple properties, and to make sure that caching and re-rendering works, we need to shallowy compare the returned objects, so we also pass in a boolean flag. We'll see how this selector function works in a while, but let's first see how the context is created.

We're actually still allowing null here to make creating the context easier. This context has multiple values, so if we had to type them all out, it would be a lot of work. Allowing null makes that a lot easier and a lot more compact. This is because this library.useContextSelector is still required as an initial value for the context. In the provider, we apply the value in the same way as normal, and you can also see here this still allows null to be passed in. But now things get complex. When we select from our context, we have this overloaded function. It allows us to either select the whole context if we pass in nothing, select a single value if we pass in a selector, or select multiple value if we pass in a selector and true. It's not pretty. It's a bit complex, but it works. But if you need this for multiple contexts throughout your application, it's very repetitive to copy around. For that very reason, I've created a small library called Recontextual which does exactly this. It wraps useContextSelector and simplifies the API. It is slightly opinionated about what the API should look like, but I think this is still very generic and can be used for most people. It does not allow a default value, but I also don't think that people use the default value of more complex contexts anyway. Let's see how we use that in ScheduleProvider.

10. Using Recontextual Library for Context Management

Short description:

We display the daily schedule and a small calendar component. The calendar component selects multiple values from the context, while the schedule selects a single value. The implementation is in a file called Recontextual.ts. The library, located on GitHub, has a small footprint. If you have any feedback, please message me on LinkedIn. Thank you for listening!

You can see it in action here. We display the daily schedule in the bottom, and in the top we can change the day and also display which day is the current day in a small calendar component.

So in the calendar component here, we select multiple values from the context, and in the schedule, we select just a single value. This is implemented here in a file called Recontextual.ts. It just requires the context type, and that's it. It returns a provider and selector function, and everything is taken care of.

In the provider, we pass in a value, and as you can see here, null is actually not allowed. It does use null internally, but it doesn't expose the fact that it uses null. So it's not allowed. We have to pass in a proper value. The library is located here in GitHub, and it has a very small footprint. I really hope that you like it and you would want to play around with it.

Those are all my tips. I'll be around for Q&A right after this talk. If you think I made a boo-boo or anything weird, or you think I'm just wrong, please throw me a message on LinkedIn. That's probably the best place to reach me. Thank you so much for listening, and please consider buying my books.

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 Summit 2022React Summit 2022
20 min
Routing in React 18 and Beyond
Top Content
Concurrent React and Server Components are changing the way we think about routing, rendering, and fetching in web applications. Next.js recently shared part of its vision to help developers adopt these new React features and take advantage of the benefits they unlock.In this talk, we’ll explore the past, present and future of routing in front-end applications and discuss how new features in React and Next.js can help us architect more performant and feature-rich applications.
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.
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 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 Advanced Conference 2021React Advanced Conference 2021
174 min
React, TypeScript, and TDD
Top Content
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
Top Content
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.
Node Congress 2024Node Congress 2024
83 min
Deep TypeScript Tips & Tricks
Workshop
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.
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.