TypeScript and React: Secrets of a Happy Marriage


TypeScript and React are inseparable. What's the secret to their successful union? Quite a lot of surprisingly strange code. Learn why useRef always feels weird, how to wrangle generics in custom hooks, and how union types can transform your components.



Two houses, both alike in dignity, In fair VS code, where we lay our scene. From forth the fatal loins of these two foes A pair of star-crossed lovers take their life. React and TypeScript, star-crossed lovers, I believe. I think they're soulmates. But a lot of people, they get into a honeymoon period with React and TypeScript, put them together, and they start to realize some things don't really click. And they never quite fulfill the relationship and never quite make it to old age. So I want to tell you the secrets of a happy marriage between React and TypeScript. How to survive the honeymoon period and the disappointment afterwards. I am the Rodney Milano of TypeScript, apparently. That's my tagline on Twitter. That's how everyone knows me. I'm MattPoker at UK on Twitter. I'm building a course called TotalTypeScript.com, which looks freaking amazing. Look at all these illustrations. Which is going to cover a huge amount of TypeScript, hopefully all of it, basically, from all the beginner stuff to all the advanced stuff. And I also work at Vercel on a different product called TurboRepo, which is real good, too. So why would you use TypeScript in React? Why not just use JSX? Well, there must be something to this, because TypeScript is enormously popular. And if you're building a React app at the moment, you're either choosing to use TypeScript, or you're probably choosing not to use TypeScript. But TypeScript is always in the conversation. So why wouldn't you just use JSX files? Well, there's a page on the React docs, which is basically type checking in React. And it's using something called PropTypes. And PropTypes, you're basically able to give a component a kind of interface to say, this is how you're supposed to call that component. And it's not bad. I mean, if you use this, and if you say, OK, I want to use this input here, then it actually does give you some autocomplete on the name here. And if I change this to ID, then I get autocomplete on the ID, too. So it's not terrible. But it's also kind of like, when you look at TypeScript, you ain't going to look at this again. The next thing is, it doesn't really enforce a contract at the component level. It gives you some hints, and it allows you to sort of document what it does a little bit. But PropTypes doesn't actually really error. It just kind of throws up an error into the console. And if you're not looking at the console, then you're not really going to see any of this stuff. It also doesn't work with hooks, either. And hooks are kind of like the main currency of React, since they dropped. And failing in the console is really too late for a failure. Like you really want to get that error as soon as possible. And if you're not checking the console, then you might just push that code out to production, and it might kind of fail. And the reason this is, is that you always want to fail earlier. The earlier you fail, the easier it is to see what happened. Because if you fail too late, and that error and that bad bit of data that you pass into your component goes through your system, then it's really, really hard to debug it. It's kind of like it's buried into your system, and you've got to extract it out. And the harder you fail, then the harder it is to ignore, too. If you're just sort of throwing up an error in the console, then that's not going to do the job, really. So ideally, you want to fail early and fail hard, just like my mama always said. And what does fail hard actually mean? Well, in your app, every time you have a component, every time you have a hook, you're basically calling that component or hook. You know, it's like a function. And when you do that, you really want the things that you pass in to be accurate. And I like to think of this as kind of like the seams of your application. Like the components and the hooks, they're like the bits of fabric that you're seaming together by calling them. My wife is like, she does dressmaking and stuff, so I'm sure she's in the next room going like, what the hell are you talking about? But the idea is if your seams are strong, then your app will be more robust. And this is how you do it in TypeScript. So you have this input here, let's say. And instead of doing this with prop types, you get to do this actually inline here. So you can say props name string. And now if I don't pass this, then it's going to yell at me, which is nice. My name is missing in type blue, required in type blue. And it's also like, if I pass it the wrong thing, it's going to yell at me too. So if I pass it with a number here, and this is like the earliest that you could possibly imagine failing. It's failing as you type. And a lot of people go, God, I really don't like this at all. It's like my English teacher is like peering over me and going, no, you did this wrong, how dare you? But I love this because it's failing as early as it can possibly fail. And it's failing really hard too. It's giving you this horrible warning just there. And often if you hook this up to your CI, then it's not going to let you push this out. So you can declare props inline like this, or you can declare them with an interface like this, or with a type too. Type or interface, doesn't matter. And then you can also do this for hooks too. So this use inputs here. It's got a params object, which has this default value string. You can also specify functions here. So value string Boolean. And you can check the TypeScript docs to learn more about this too. And if I return the wrong thing from this, if I just return a number here, then it's going to yell at me because number is not a simple type Boolean. So it's not just functions and, oh sorry, hooks and components. It's all functions really, and a bunch of other stuff too. So again, you can declare this with interface or you can declare this with a type too. So you might think I'm in love. This is so much better than the prop types rubbish I was dealing with before. But soft what light through yonder window breaks is type safety and TypeScript is the sun. And this is what the experts call a honeymoon period. This is the bit in your relationship before you start sharing a fridge. And as you go further down here, you start thinking, okay, how do we make this relationship last? What are the stresses on this relationship? How is it going to cope going forward? Now the big stress that comes in is that the contracts you specify at these scenes, your function calls can sometimes be really, really complicated. And if you think about this problem here, we've got a button and it's kind of like one of those buttons that you might've seen before where if you pass in a ref, I know it's href, I always call it href, so bear with me, then it renders as an anchor. If you pass in, if you don't pass in an anchor, oh sorry, if you don't pass in a href and you pass in an on click instead, then it renders as a button. And so you can like, it kind of unifies your styling a little bit and means you can do like buttons and anchors and different things. But imagine that you accidentally pass in a href and an on click. Hmm. What's going to happen here? Well this on click is actually going to be ignored because of the logic that's up here. And this is a JavaScript file, so it's not giving us anything. We also can pass nothing to this if we want to. And this just seems silly because now we've got a button that does nothing and really our buttons, we want them to be doing hrefs and on clicks. So how would we solve this in TypeScript? Well you know, you're in your honeymoon period and you're thinking, well, I'm this beautiful, wonderful person. So you use optional properties. You say, okay, you don't need to pass a href and you don't need to pass an on click. And we'll just sort of add them like this. And again, your logic stays the same, which is nice. And but this again, like it's a little bit dodgy. Both the href on click can still be provided or we can still pass neither. These are still valid. So how do we make TypeScript go with us and say you can either pass a href or an on click? Well, you can use this kind of like dynamic props pattern. And what this is doing is it's saying you can pass a href, which is a string here, or you can pass an on click void here. And it's basically saying these two objects can exist kind of separately. And so what we say is we combine our kind of normal props up here with the children that we have and the dynamic props. And so you end up with a button where you have ignored these errors for now, which does actually error when you don't assign either one. So now we can pass in a href or we can pass in on click, which is very, very nice. But we've got an issue, which is it's actually erroring inside the components. We could do some like, you know, funky stuff inside here with props as any, but then we've got to do that like everywhere. So why is this erroring? Well, it's saying that you can either pass in a object with a href or an object with an on click. And you can't actually like narrow down the props object by just accessing something on it. Like TypeScript won't let you do that. So we need to refactor this slightly to use a check here. So if href in props, which this is just valid JavaScript, then what is that checks that it has a href attribute inside props. And then what that means is that you actually have href in here, which is nice. And it means that since we're returning inside here, then props, it has a href on it in this closure, but it actually has a props.onClick in this closure. So TypeScript is really useful here. And that now means that it's like happy outside the components and happy inside the components, which is great. And this is called a union type. And I really recommend using these like union types in props can solve a lot of issues that you think you need more complicated tools to use, but actually you just need a union type. There is like more stuff here. Like another problem that can occur is when you have some like props that you think that are kind of dependent on each other. We've got rows here and then render row, and we use it kind of like this. We pass in the rows into our table, name John, name Vakas, and then we have render row. But this row, its type is unknown. Now that's dumb, that's stupid. Why didn't you understand me? We know that it's this type, right? So we'll end up having to do like name string, you know, just to make the other person happy. But this actually isn't assignable. So type unknown is not assignable to type that. So we end up having to go up here and do any instead. But we've really lost a bit of type safety here. And like if we add in ID here, you know, ID number, then this isn't actually present on the rows up here. So these two can get out of sync. And this kind of out of sync feeling is really, really dangerous for relationship. So the solution is, in fact, let me fix this from the other angle. The solution here is to kind of like communicate dynamically and to say, when you call this table, I'm going to listen to you. TypeScript is going to listen to you and say, okay, whatever is in here also needs to go in here. So these two things, whatever they are, they're going to be the same thing. And then you can add this little, this is called a generic up in here. And it's kind of like a type argument. So if I wanted to create a new type out of this, I can say my table props equals table props. And I can just pass in anything to this. So I can say name, string, ID number, whatever. And then I end up with rows or actually if I go const props is my table props, then I can say we have rows and that now must be ID and name. So this is kind of like a way of inserting a type into another type. It sort of turns table props into a function. So I can say T row inside here, I'm going to add T row onto this little generic slot here. That lets me, if I want to pass a type argument along with my regular arguments to this function. Now that, what that's going to do is if you don't end up passing a type argument, it's just going to infer it from up here. And what we end up with is actually if I delete this bit here, now we have name jar, name back ass, and the row is typed as name string. If you hover over this table here, you can see that it's got this little T row thing here, which is very, very useful. And if we add another property to this ID one, for instance, then I'm going to be able to access ID on this thing too. So I can say the key is now row.id, putting to give back as an ID too. There we go. Extremely useful for when you have different properties in the same kind of props object, which all rely on each other. You can add this kind of generic syntax here and you can even make sure that it like corresponds to a certain thing. So if you always want to pass in like an ID here, then it's going to enforce like that property there. So now we're saying T row must extend ID number. This extends keyword is like really horrible. It props up in a bunch of places. But what it means is this is constrained to be this shape now. So if I don't pass an ID here, then it's going to yell at me because props ID name is not assignable to type ID number. And now I have to pass an ID. That means I'll always have a key here too. Very, very useful. So this idea then is like, it's basically a generic in a component prop. It's really powerful for syncing types together into the same component, essentially, so that you end up with these really powerful dynamic contracts. I can go and reuse my table components in a bunch of different places. And no matter what data I'm passing in, the component will be able to understand it. Because really, this is just a wrapper around this render row function. Yeah, I've used this pattern before and production is freaking amazing. So another thing that can like catch you out is React built in types. Now these are actually maintained separately from React itself. React isn't written in TypeScript. It's written in Flow, I think. And what it does then is like, you have to install React and then install types React. And the kind of like, because they're not built together, they can often kind of like, the types are doing something slightly different to the actual React core, not in a dangerous way, but there's just some stuff that's in the types that React itself hasn't documented. And this can be really, really painful. So let's go with like a simple one here, which is let's say you have a number in our state. Now as predicted, if you start off with like a number in your use state here, then this state is going to be typed as number and set state is going to be typed as number two. So I can't pass in a string into this, I'm going to have to pass in a number. And these are all sort of built in parameters in React, of course, if you use it. Now what happens then if I don't actually have a value to pass in here, but I still want this state to be typed as a number? Well, you can pass this a type argument. And so you can say, okay, this use state is now a number. And you might think that state now is typed as number because I can set state to number, but it's not, it's actually typed as number or undefined. And that's correct because the first render here, before I set my state, imagine if I do this in like a, I know this is a bad practice nowadays, not very fashionable, but let's say I just like set my state to one inside this use effect. Well, on the first render state is actually going to be undefined because I'm passing nothing to this. And whereas if I actually pass it a number, then it's going to be defined on that first render. Now, the way it can do this, the way it knows how to do this is if we command click into use states here, we end up in this very, very terrifying file. And of course I've immediately lost my place. Where we're basically inside the type definitions for all of these hooks. So we've got use context, we've got use state, you know, oh hello guys, all the gangs all here. And what we've got then is we have a function overload on use states. Use state can be called in two different ways depending on what you want basically. So this first overload here, this is really hard to read. So let me sort of break it up a little bit. What's going on is that use state, it's a generic function, seen a generic before, and it's saying the initial state is this S or a function that returns S. Don't save my changes please, I don't want to be responsible for breaking anything. So that means then that I can pass in this type argument and I can either have a function that returns a number or I can just pass in the number itself. Okay, makes sense so far. Now the second overload is saying if I don't pass anything, then the thing that gets returned is S or undefined, whereas up here it was just S, right? And what that means then is that if I don't pass anything here, I'm going to end up with number or undefined. And there's only two overloads in use state, which is kind of nice, but it's pretty important to get right so you don't end up with undefined accidentally kind of invading your types. The really horrible one though is use ref. So if we go into use ref, like this is a really nasty error to debug. Immediately. Oh, disgusting. Mutable ref object, legacy ref object. And the solution to this is deeply counterintuitive. There you go, that's it. Why does that work? Well, if we go into use ref, then we'll see that there are several overloads on use ref, and what we have is we have three overloads. We have a use ref where the initial value is T and it's passed in and you end up with a mutable ref object. So if we look inside, here it is. We have our number here and then overload one, you end up with react mutable ref object. So if I say overload one dot current, I can actually assign this to something different. But on overload two here, if I pass in a number, or sorry, if I pass in a type argument of number but pass in null, I can say overload two dot current equals three or whatever. I can't reassign to it. What? I mean, this looks like exactly the same. Surely this should be typed as like overload two is like thingy or null, right? Well, I'll show you why this happens in a second or why this is here. And if I don't pass anything, then it's going to let me be mutable again. So overload three dot current equals two. So the reason this is in place is so that like there are some refs that react needs to control and there are some refs that you can control. And in general, the ones that react wants to control is where you're passing it directly into developments, essentially. And the way that react tells you to do this is with this null property. So if you don't pass in null, it's going to yell at you. But if you do pass in null, it is going to yell at you. And this kind of like these use refs are really important to understand because this can really like give you so much pain in terms of when you're using react and using use ref. But I think this is basically my time. If you want to learn more about this stuff, then, you know, come talk to me afterwards and find me on Twitter and ask me questions about TypeScript and react. There's so much you can dive into, and it's a really, really deep topic. But truly, I think it can make a successful marriage if you iron out these difficulties and really understand where both sides are coming from. Thank you.
21 min
24 Oct, 2022

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