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.
TypeScript and React: Secrets of a Happy Marriage
AI Generated Video Summary
React and TypeScript have a strong relationship, with TypeScript offering benefits like better type checking and contract enforcement. Failing early and failing hard is important in software development to catch errors and debug effectively. TypeScript provides early detection of errors and ensures data accuracy in components and hooks. It offers superior type safety but can become complex as the codebase grows. Using union types in props can resolve errors and address dependencies. Dynamic communication and type contracts can be achieved through generics. Understanding React's built-in types and hooks like useState and useRef is crucial for leveraging their functionality.
1. Introduction to React and TypeScript
React and TypeScript are like star-crossed lovers. Many people enter a honeymoon period with React and TypeScript, but they eventually realize that some things don't click. However, there is a secret to a happy marriage between React and TypeScript. TypeScript is enormously popular in the React community, and it offers benefits that JSX files and prop types don't provide. TypeScript provides better type checking, auto-complete, and enforces contracts at the component level. It also works seamlessly with React hooks, which are essential in modern React development.
♪♪ 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. You know, 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 secret of a happy marriage between React and TypeScript, how to kind of survive the honeymoon period and the disappointment afterwards. I am the Rodney Molinow TypeScript, apparently. That's my sort of tagline on Twitter. That's how everyone knows me. I'm mattpoco.uk on Twitter. I'm building a course called totaltypescript.com, which looks fricking amazing. Look at all these illustrations, which is going to cover like 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 Vassell on a different product called TurboRepo, which is real good too.
So why would you use TypeScript in React? Like why not just use JSX? Well, like 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 like JSX files? Well, there's a page on the React docs, which is like basically type checking in React. And it's using something called prop types. And prop types, 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 not bad. I mean, like if you use this and if you like say, okay, I want to use this input here then it actually does give you some auto-complete on like the name here. And if I change this to like ID, I'll get auto-complete on the ID too. So it's not terrible, but it's also kind of like, when you look at TypeScript, you ain't gonna look at this again. The next thing is like, like it doesn't really enforce a contract at the component level. It gives you some hints and it allows you to sort of, it sort of documents what it does a little bit, but prop types 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.
2. Importance of Failing Early and Failing Hard
Failing in the console is too late. You want to catch errors as soon as possible. Failing early makes it easier to debug and extract the error. Failing hard means not ignoring errors. It's important to fail early and fail hard.
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 sort of thing, like that bad bit of data that you pass into your component kind of 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. Ideally, you want to fail early and fail hard, just like my mama always said.
3. Failing Early and Failing Hard in TypeScript
In TypeScript, you can ensure the accuracy of data passed into components and hooks by defining their types inline. This allows for early detection of missing or incorrect properties, resulting in a more robust application.
And what does fail hard actually mean? Well, in your app, like 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. You know, your, my wife is like, she does dressmaking and stuff. So I'm sure she's 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 like, 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 in line here. So you can say props named string. And now if I don't pass this, then it's going to yell at me, which is nice. Property 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.
4. Benefits and Challenges of Using TypeScript
TypeScript allows for early detection of errors as you type, providing a robust and efficient development experience. It supports inline declaration of props and hooks, with the ability to specify types for parameters and return values. TypeScript offers superior type safety compared to prop types and helps establish a strong foundation for your codebase. However, as your codebase grows, the complexity of function contracts can become a stressor. Careful consideration of function calls and their contracts is necessary to maintain a healthy and lasting relationship between TypeScript and your project.
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 like your CI, then it's not gonna let you push this out.
So you can declare props kind of in line 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 gonna yell at me because number is not a simple type Boolean. So it's not just functions and 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 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 stressor 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, but I always call it ref, so bear with me, then it renders as an anchor. If you don't pass in an anchor, oh, sorry, if you don't pass in a href and you pass in an onClick 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 onClick. Hmm, what's going to happen here? Well, this onClick 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.
5. Dynamic Props and Union Types in TypeScript
We can use optional properties in TypeScript to allow for the passing of href or onClick, or neither. However, this approach can lead to errors. To solve this, we can use a dynamic props pattern with union types, which allows for the separate existence of href and onClick. By combining normal props with children and dynamic props, we can create a button that enforces the presence of either href or onClick. This approach resolves errors both inside and outside the components, providing a more robust solution. Union types in props offer a simpler alternative to more complex tools and can address dependencies between props.
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 onClicks.
So how would we solve this in TypeScript? Well, you know, you're in your honeymoon period and you're thinking, wow, 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 onClick. And we'll just sort of add them like this. And again, your logic stays the same, which is nice. But this again, like it's a little bit dodgy. Both the href onClick 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 onClick? 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 onClick 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 ignore these errors for now, which does actually error when you don't assign either one. So now we can pass in href or we can pass in onClick, 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, we can say props as any, but then we're gonna do that like everywhere. So why is this erring? Well, it's saying that you can either pass in a object with a href or an object with an onClick, 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. 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 more stuff here. Another problem that can occur is when you have, you have some props that you think that are kind of dependent on each other.
6. Understanding Type Safety and Sync Issues
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. So we'll end up having to do like name string, just to make the other person happy. But we've really lost a bit of type safety here. And like if we add in an 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.
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? Like we know that it's this type, right? So we'll end up having to do like name string, 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 an 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.
7. Dynamic Communication and Type Contracts
The solution is to communicate dynamically and ensure that the props passed to the table component match the expected structure. By using generics, we can create a new type that enforces the correct structure of the props. This allows for the creation of powerful dynamic contracts and enables the reuse of table components in various contexts.
So the solution is, and 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. 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. This sort of turns table props into a function. And so I can say t row inside here, and I'm gonna add t row onto this little generic slot here. That lets me, if I want to, pass a type arguments along with my regular arguments to this function. Now that, what that's gonna do is if you don't end up passing a type argument, it's just gonna infer it from up here. And what we end up with is actually if I delete this bit here, now we have named jar named vacas, 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 gonna be able to access ID on this thing too. So I can say the key is now row dot ID, putting to give vacas an ID two, 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 gonna 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 like 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 gonna yell at me because props ID name's not assignable type ID number. And now I have to pass in ID, and 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. And it's really powerful for syncing types together to 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.
8. React's Built-in Types and useState
React's built-in types, maintained separately from React itself, can cause confusion. Passing a type argument to useState can ensure the state is typed correctly. The first render may result in undefined if no value is passed. Understanding the type definitions for hooks like useState is essential for leveraging their functionality.
Because really this is just a wrapper around this render row function. I've used this pattern before in production is freaking amazing.
So another thing that can like catch you out is React's 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 of 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 gonna be typed as number and set state is gonna be typed as number two. So I can't pass in a string into this, I'm gonna have to pass in a number. And these are all sort of built-in parameters in React, of course, if you use them.
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 you 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 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 you state here, we end up in this very, very terrifying file. And of course, I've immediately lost my place where we 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 useState. You 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 useState, it's a generic function, we've 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 wanna be responsible for breaking anything.
9. Understanding useState and useRef
In useState, if a type argument is not provided, the return type can be S or undefined. It's important to use useState correctly to avoid unexpected undefined types. useRef has multiple overloads, including one where the initial value is passed in and returns a mutable ref object. Another overload accepts a type argument of number and null, preventing reassignment. Understanding the use of null in useRef is crucial for controlling refs in React development. If you want to learn more about TypeScript and React, feel free to connect with me on Twitter.
So that means then that I can parse in this type argument and I can either have a function that returns a number or I can just parse in the number itself. Makes sense so far. Now the second overload is saying if I don't parse anything, then the thing that gets returned is S or undefined, whereas up here, it was just S. And what that means then is that if I don't parse anything here, I'm going to end up with number or undefined. And there's only two overloads in useState, 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 useRef. So we're going to useRef like this is a really nasty error. It's a debug. Immediately. Disgusting. Mutable ref object, legacy ref object. Blah, blah, blah. And the solution to this is deeply counterintuitive. Whoa! There you go, that's it. Why does that work? Well, if we're going to useRef, then we'll see that there are several overloads on useRef, where what we have is we have three overloads. We have a useRef 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, where is it? Here it is. We have our number here and then Overload1, you end up with React Mutable Ref object. So if I say Overload1.Current, I can actually assign this to something different, but on Overload2 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 Overload2.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 Overload2 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 gonna let me be mutable again. So Overload3.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 development 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 gonna yell at you but if you do pass in null it is gonna 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 these refs.
But I think this is basically my time. If you wanna learn more about this stuff then 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.
Comments