We are slowly getting to a point, where TypeScript-support is a must-have feature of a framework and not a nice-to-have. But this is not a simple yes or no question. Let's take a look at the different framework areas where TypeScript can help you develop quality applications.
How Typed is Your Framework?
AI Generated Video Summary
Today's Talk focused on the importance of TypeScript in preventing runtime errors and its integration with popular frameworks like Vue.js, Angular, and React. TypeScript provides error assistance and typing boundaries between components, ensuring correct usage. It also allows for the creation of generic components, leveraging TypeScript generics to define contracts between unknown properties. The Talk highlighted the use of TypeScript in various scenarios, such as working with React Node, and provided resources for further learning and exploration.
1. Introduction to TypeScript and React
Thank you for having me. Today, I want to show you some code snippets and discuss the importance of TypeScript in preventing runtime errors. I will also talk about how typed React is compared to other frameworks. My name is Andreas, and I'm a development leader from Dresden, Germany. Since 2016, we have migrated all our projects to TypeScript and have become great fans. Many popular frameworks now offer first class TypeScript support.
♪ Thank you very much for having me. You cannot imagine how excited I am to be here today. It's fine that the slide is black, it's all good. Hello, everyone, as well to everyone who's watching remotely. I hope you're enjoying the conference.
Before I'm going to introduce myself, I want to show you some small snippets of the code and ask you one simple question. Does this look like fun to you? When we take a look at this, it looks innocent enough. We push it to production, run our code and run into this beautiful runtime error. Uncaught reference error, route is not defined. Of course, those runtime errors always show us the little line where the error happens in our code. So easy enough, we can spot that we just made a small little typo there. So, of course, we fix the typo, call it a day, push the code to production, go into the weekend, and, of course, Saturday morning, the client calls and tells us it's still not working. We ran into another runtime error.
Errors like these are exactly the reason why TypeScript has risen in popularity over the last couple of years. Because, of course, the main promises, those type of problems and errors will never appear at runtime if you're working with TypeScript. So you're going to your tech lead and convince him to convert, to migrate your complete code base all the way to TypeScript. Because maybe it's an older project and you're still working with class components and we're even using legacy APIs, like the legacy StringRefs. So as you can see, this is already TypeScript code, but they are still the same runtime error. Here we are passing a StringRef down there to the div to get a reference to the HTML node and at the string root. And we access this at the top with this.refs.root, but again with the same typo. As you can see, only because we are using TypeScript it does not guarantee that we will not run in any runtime errors. It depends on the framework, it depends on the APIs that we are using how safe we really are. And this is exactly the topic of my talk that I'm going to give to you now. How typed is React really, and how does it compare to other frameworks?
2. TypeScript in Frameworks
TypeScript is a first class citizen in our framework. Vue.js and Angular have embraced TypeScript, offering better experiences. React, while stagnating, still benefits from TypeScript. TypeScript supports us in the basics and helps with errors and suggestions. It can also crash the build pipeline for typos. When using more features, TypeScript allows for typing boundaries between components.
TypeScript is working out of the box. First, the TypeScript is a first class citizen in our framework. Funnily enough, maybe you saw it already, yesterday they released the newest version of the React documentation as an early beta and I searched the docs and so far nothing like that is in the beta documentation, but we will see maybe it will be added at a later point in time. Maybe take a look at the popular frameworks.
A lot has changed over the last previous years. First of all, Vue.js when they announced Vue 3.0, they announced that they have completely rewritten the framework based on TypeScript and they are able to offer a much better experience than with the earlier versions of Vue. Angular as well, even if they started with TypeScript all those years ago, they started actually so early with TypeScript that TypeScript was not yet powerful enough to model all those dynamic features that the framework needs to offer its users. Sadly, on the React front, things have been a bit stagnating. But, this is not a problem at all because from the beginning, when TypeScript made the decision to directly support JSX or TSX, we never had any problems with the TypeScript support, so on that front, even if not much has changed, we can still get the benefits of TypeScript in our language.
3. TypeScript and Component Boundaries
TypeScript forces us to check if the variable x is a number before accessing number functions. Vue.js has a similar feature to catch errors in templates. We can now define type-safe logic and access it in our templates. TypeScript helps us ensure correct usage of components and provides error assistance for inputs and outputs.
So when we directly call the toFixed function on x, TypeScript can offer us this help for error and tell us it's all good that toFixed exists on a number, but on the type string, the function toFixed does not exist. So TypeScript forces us to first check if the variable x really is a number. And only then can we access the functions that exist on numbers.
This is a feature that has only been added to the other frameworks quite late actually. For example, here we are seeing the equivalent vue.js code. We have basically the same thing if defining a property that is either a number or a string and we're using it in the template. And we are getting exactly the same error as earlier because vue.js, they found a possibility to compile the templates into real TypeScript code and have the same kinds of errors that we get natively by the TypeScript compiler in React.
Now we have the basics down so we can define the logic of our components in a type safe manner. We can access this logic in our templates and have TypeScript help us all the way. Now let's jump into the boundaries between components. Like right here, we have our component B which receives as an input a value x as a number and it provides an output which is again a number. When we're now using that component on the right, of course we want to make sure that we are using this component correctly. So right here we are passing in a string instead of a number, TypeScript can help us there. Same thing with the outputs, we defined that set x is always called with a number so there again we get the help from TypeScript.
4. React Components and Virtualization
React components are just functions, allowing us to access the shape of component arguments. We can extract props using TypeScript helpers and component props. This is useful for defining thin wrappers around components and exchanging components in a type-safe way. Virtualization is a technique to render only visible elements in a list.
A very interesting thing is that these kinds of errors are not supported in all major frameworks. For us React developers it's quite natural that if we define two properties, x and set x, then we have to provide these when using the component but this is not a given in all other frameworks. Now we have the basics down and as I said earlier, especially since the latest changes in the other frameworks, they have really caught up with React on that regard but there are still some cherries on top that React is offering us that the others can't or cannot quite easily give us as developers.
So for example, right here we are extracting all properties that the native HTML element is allowed to receive. This is very useful to define very thin wrappers around other components. For example, right here we want a small wrapper around the HTML button component where we are able to pass in another property, an icon. So we are just extracting all properties from the HTML button element and joining with the intersection operator, joining some new properties like here, the optional icon prop. In our component, we can then just destructure our props, pass in the icon and use it in our component some way or another, and pass in the rest props down to the button. And the nice thing is that if for some reason HTML adds another property to the HTML button, this still works and it's still completely type safe. So we don't have to repeat all props that are present on the HTML button, but can just take the props from the HTML button and join them into our prop types. We can also leverage this pattern to exchange components in our applications in a type safe way. So here, for example, we have this customizable application. There we are defining as an argument, we want to receive any component that fulfills the interface of our button component. This way, we could build a framework where the buttons are themable, exchangeable, have different behavior, and users of our framework can just apply their own button component, which will be used everywhere in the application. And we still have this in a type safe way. So they have to make sure that their button component complies with the interface of this button props element. Next, we want to take a look at another great feature that we receive by having the components being only functions. Maybe you heard the talk earlier about virtualization. Virtualization is a technique where you don't want to render all elements in a list but only the elements that are currently visible on the screen.
5. Building a Generic Component with TypeScript
We build a component that can be used with different types, ensuring type safety. TypeScript generics allow us to define a contract between unknown properties. This way, we can pass in lists of different types and still receive the correct object in the RenderItem function. TypeScript correctly infers the type of our component. The ASPROP pattern is another popular use of this feature.
And here, we are building a small dummy component that is doing exactly that. We defined the interface here with receiving an item count and an item height. This makes calculation quite easy which elements are currently visible in the viewport, and we pass in a render item, render prop, which we can use to define how each element is being rendered in the UI.
Of course, we then have to make some calculations to calculate which elements are currently visible, we're going to skip that for now, and then we are just iterating over the visible indices and call the render prop. When using this component, it looks currently something like that. So we fetch the data, it's a person array in our use case and we want to use our virtualized list to render those persons to the UI. Here, because we defined that the index of render item will always pass out a number, we are working in a type-safe way. So we accessing an index on the person's list and accessing the field name or age.
The problem is that maybe we don't always have a list available. Maybe it's a lazy loading list where we just fetched the data on scroll, it's an infinite loading list, for example, so maybe we don't have an array where we have all persons available. So optimally we want the API to look like this. Render item now gives us a person object and on the person we can access name and age and no other fields, because only these two exist.
The problem is, when thinking about this naively, we might think that we now have to develop a virtualized list for persons, a virtualized list component for cars, a list component for pets, et cetera. And of course, this cannot be the right solution. So maybe at first we are changing the interface of our virtualized list component to receive unknowns or any props. This way, when using this component, you can pass in a list of persons, a list of cats, a list of animals and it will work. The problem is on the output side of things, render item will pass us an item element of the type unknown.
So we cannot use it to access the fields age and name because unknown does not have any fields. So now we would need some kind of a contract that we can use to connect these two unknown properties. And for this, we can use TypeScript generics. So we define this TitleGenericType variable that we can then use to define that items is of any type with TItemArray. And when used with the type person, for example, then we want render item to give us back a person again. So when using this component, we can pass in a list of persons and TypeScript will know that we instantiated the component with the person type and will receive the person object in the RenderItem function. When we hover over this JSX element, we get this tooltip where we can see that TypeScript correctly inferred the type of our component. This way, we can build a component that can be used with different kinds of types. So with persons, cats, cars, whatever. And we're still being completely type safe when using this component.
Another quite popular pattern that is using this feature is the ASPROP. Maybe you've used it in style components or in motion where you can pass in another component in the ASPROP and want to pass in new properties to this new generic component. So like right here, we have this link component which normally renders just in A-Tag maybe in the UI.
Using TypeScript Generics and React Node
We can make use of TypeScript generics to define our component and achieve a nice usability. TypeScript support goes beyond defining types in logic and templates. There are many additional use cases where TypeScript can be leveraged in React projects. It's okay to use 'any' within a module, but never let it out. React node is more flexible than JSX elements as a return type. The error messages from TypeScript types can be challenging, especially with GraphQL and code generation. There is always room for improvement. If you have to choose between 'any' and 'unknown', use 'any' within a module and 'unknown' when expecting external variables.
But right now we want to render it as a button element and we want to be able to pass in an additional icon. And here again we can make use of the TypeScript generics and define our component like that. You can see maybe one of the problems when working with TypeScript a lot. The component code, library code starts to look quite complex but we're achieving a very nice usability for the users of our component.
Like right here for example, we define the type variable T-Component. We add this constraint that it has to be a component type. And then we can say that our link component will receive the S-Prop where we can pass in any component and it can receive all props that this passed component wants to receive in the UI. So now I hope that you could see that yes, TypeScript support is good and all frameworks have the basics down of the TypeScript support but TypeScript support is more than only defining the types inside of our logic of our component, inside of our templates, also between on the boundaries between components but also, there are lots and lots of additional use cases where we can leverage TypeScript in our react projects.
I want to say thank you for listening to my talk, I hope that you have some quite exciting questions for me right now. I wish you a lot of fun at the remaining conference and want to say thank you. Thank you so much.
Would you like to grab a seat? We've got a couple of questions and I'm pretty sure that more questions will be rolling in as we go along. So, one of the first ones, and I kind of like this one because I guess it goes against everything that TypeScript is supposed to offer. Is there ever a good excuse for using the any type in your project? Yeah. There absolutely is. So, the only thing that you really never, never, never, ever must do in your projects is letting an any out of a component. So, it's absolutely okay to use an any within one function, within one module, because maybe the types, you're building a lookup object, for example, where you don't yet know all the fields that will be present on this lookup object, then, just slap an any on that, add the fields later, but make sure that the return type of your function is typed correctly. But within a small module, you can just add an any, maybe write a unit test to be absolutely sure, but it's absolutely no problem to use it within a module, but never let it out of the module, because then it will spread like wildfire. Never let any out, definitely.
Next question, when would you use React node over JSX elements as a return type? So, personally, we almost always use React node, because it's a bit more flexible. So, React node is basically everything that is renderable by React, so, not only a JSX element, but also null, undefined, true, false, strings, numbers, and whatever, so, just a bit more flexible. Nice. And, another question, what do you think is the weakest or hardest part of working with React and TypeScript? I think the hardest part is the error messages that types will give you. Especially maybe one of you, you have experience there, when you're working with GraphQL and write a code generator for your GraphQL types, you receive this massive typed object that, yes, they exactly show you what type of field you receive from the backend, but when one field is missing there in your, maybe you pass it to a component, one field is missing, the error message is just, it's so huge and new developers have, or even intermediate developers, really struggle with identifying where really the error is in this typed message, and this can get really quite confusing, and this is something that still needs improvement, as I say. Always room for improvement. And kind of going back to the question earlier about any, which do you prefer to use, any or unknown. If you absolutely have to, obviously you're never gonna let it get out of the component. So, I'd say within one module, element, function, whatever, I'd say it's fine to use any because then you're just free to do whatever you want with that variable. If you have a case where you're expecting some kind of variable from outside, so you're writing your own console log function, maybe, and users can just supply any value they want, I'd use an unknown, because then I can't accidentally use any fields on this data, because I won't know what data is getting passed in. For example, if I write a log function that just says JSON.stringify, then it really doesn't matter.
Approaching TypeScript and Resources
When using TypeScript, it's important to think about all aspects from the design phase and avoid making assumptions. For teams new to TypeScript, it's recommended to use existing libraries with strong TypeScript support. TypeScript and React cheat sheets by Shawn Wang are great resources for learning advanced patterns. Understanding the relationship between input and output types can help in solving complex problems. Unfortunately, we have run out of time for questions, but there are other opportunities to ask during the break and join the Spatial Room for further discussions.
So, I just write unknown there and can be sure that I won't access any fields that don't exist. I think it's also good because it's really actually thinking about all of these things from the design phase and not making any assumptions.
And TypeScript is becoming much more widespread, right? But obviously, there's always new people who are getting started. What are the best resources to go to for people who are coming from, what are the best resources for people to go from basic TypeScript skills to start using some of those advanced patterns that you talked about? So I'd say one really good place is are the TypeScript and React cheat sheets that Shawn Wang has published on GitHub. And other than that, I always recommend, Kenzie Dots has written a blog post, sync state, derive state, and don't sync it, or something like that. And I think this is something that you can really bring into your type, thinking about types as well. Because when you have a type for the type of data that is returned by your API, for example, and you want to map this type to form fields which have a changed field, a touched field, dirty field, whatever, then you have to recognize that this new shape is completely dependent on this input shape, and that you can somehow probably map this input type to this expected output type. And once you recognize that, then you can start looking for solutions of how you can achieve this mapping and learn these more complex pattern on the way. Because that's how you learn new things by solving problems.
Thank you so much. That's all the time we have for questions today, but I can see there are so many more questions. Walk up over and ask him some of your questions during the break that we have after. And also remember there'll be a Spatial Room where you can also join in virtually and have a chat. Can we all give a massive round of applause for Andres.