How Typed is Your Framework?


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.


Thank you very much for having me. You cannot imagine how excited I am to be here today. It's all good. Hello, everyone, as well to everyone who is 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 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, so we push it to production, run our code and run into this beautiful runtime error. Uncaught reference error, root 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 promise is 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 your migrate, your complete codebase all the way to typescript. Because maybe it's an older project, we're still working with class components, and we're even using legacy APIs like the legacy string refs. So as you can see, this is already typescript code, but there's still the same runtime error. Here we are passing a string ref down there to the diff 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. So 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? But first, I'm going to introduce myself because I guess most of you won't know me. My name is Andreas, and I'm from Dresden in Germany, and I'm a development leader at a small agency. And something around 2016, we started off migrating our first project to typescript, and since then, we have been great fans. So every new project that we are starting, no way we are starting with javascript, it has to be typescript or else we are out. And I guess many of you or some of you are sharing a similar journey. And this rise in popularity has led many of the popular frameworks to add a sentence like this to their documentation. We offer first-class typescript support. typescript is working out of the box. 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 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. Later 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. In the following, I want to take a look at different areas of the framework that can be supported by the framework. At first, we're going to take a look at the basics. So within one component, you have this logic part where you call functions, you define variables, and you pass these logic parts to the template, and this template is then accessing those variables. But this is only the basics. So it's really the lowest level of typescript support that a framework can offer. The minimum requirement to really be able to help us as developers is when the boundaries between components are typed as well. So the inputs, the data that is flowing into our components, and the output, the events that flow out of it, they have to be type-safe as well to really bring us any benefits. But let's start with the basics. First, maybe we're not even working with typescript, maybe we're still working with javascript. typescript can already help us in our framework of choice. Here we maybe reinstalled the react type definitions into our project, so when we type react.use, we get an autocomplete, we get a suggestion of which functions we want to use right there. Later, we migrate our project, and then we're still in the logic part of our component, but already here, typescript can support us and help us and show us errors when we made a small little typo or used a function that does not exist. When we then want to use this data, this logic in our templates, typescript again wants to help us. So here we define some number, and we want to use it in the UI, in the template part, and here as well, typescript can help us and give us the right suggestions. And as you see on the right, when we access a function that does not exist, again, we see the error in the editor. One very important part is that we don't only want to see the error in our editor, because when we write code, maybe we are too fast for typescript in the background when it's compiling, sometimes it takes a bit, maybe you already closed your file, pushed to production or pushed to your pipeline, and then we want to be able to crash the pipeline if we still have typos in our project. So the framework has to offer a possibility so that we can run the type checks with a command line tool. Luckily, because typescript directly supports JSX, we can just run TSC, the typescript compiler, and have the errors crash the build pipeline. In the next step, it can get a bit more complex when we want to use more features that typescript is offering us. Like right here, we have our component that receives as a prop a value x, which is either a number or a string. So of course, we cannot be sure which we got in our use case. 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 the 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, defining a property that is either a number or a string, and we're using it in the template, and we're getting exactly the same error as earlier, because vue.js, they found a possibility to compile the template into real typescript code and have the same kind 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. 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 define that set x is always called with a number, so there again we get the help from typescript. 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 in 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. First of all, the great thing about react is that components are just functions. As the documentation says, it's just javascript. It's beautiful assembly. Like right here, we have our button component, maybe it's even from a library where we have typed props. The problem is maybe this library does not export this interface as an explicit type, but it only exports the component. But because in react the components are simple functions, we can use typescript helpers to access the shape of this argument. We can just use the parameters type, extract the interface and extract the type of the button function, and the parameters type will return to us a list of all parameters that our function expects. So right here in our example, a react component always receives one argument, the props object, so we use index zero to extract the props of our button component. So just because the library author decided to not directly export the type of the button component, we can still access it with parameters. However, right now this only works with function components, but luckily the react type definitions export a helper type called component props that we can use to access the props of function components, of class components, and of the built-in html elements. 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 of the 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 is 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 supply 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. And here we are building a small dummy component that is doing exactly that. We define 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 some 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're 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 fetch 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 list component for cars, a list component for pets, etc. 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 T item generic type variable that we can then use to define that items is of any type with T item array. 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 we will receive the person object in the render item 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 while 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 an A tag maybe in the UI, 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, the library code starts to look quite complex, but we are 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 ASPROP 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 this typescript support, but typescript support is more than only defining the types inside of our logic of our component, inside of our templates, also 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 project 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 your 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 fields you receive from the backend. But when one field is missing there, maybe you pass it to a component, one field is missing, the error message is just, it's so huge and new developers, or even intermediate developers, really struggle with identifying where really the error is in this type 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 going to 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 there are 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, 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. Absolutely. Now, you spoke at the beginning about oftentimes there are many people moving from javascript over to typescript, and how do you recommend approaching typescript to a team that is new to use it or has never used it before? So I'd say I think Mark Erickson from react, from the Redux team, always makes this distinction about being an application-level developer and a library developer. And using typescript at the application level is really quite comfortable because you get the autocomplete, you almost never have to specify the types yourself, typescript can infer many types. It only gets really complex when writing your own libraries. So maybe I'd say for a team that is mostly of new typescript developers, I'd say use existing libraries like react, like a form library that already has strong typescript support so that you won't have to write those library typings for yourself at first, but you can always do that later, of course. And typescript is becoming much more widespread, right? But obviously there's always new people who are getting started. So 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 the typescript and react cheat sheets that Sean Wang has published on GitHub. And other than that, I always recommend, Kenzie Dodds has written a blog post, think 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 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. So please come over and give him and ask him some of your questions during the break that we have after. And also remember there will 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? Thanks a lot.
25 min
22 Oct, 2021

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

Workshops on related topic