React-ing to TypeScript

React-ing to TypeScript

Lessons learned from my first experience building a TypeScript React app

ยท

10 min read

I Finally Gave In

I don't know about you, but I've always been afraid of TypeScript. I mean, it's still JavaScript, just more... typed. I guess what scared me the most about it is that I've never written a line of code using any strongly typed programming language. Yes! I never learned Java, Ruby, or any other strongly typed programming language. I believed that it would only be understood by developers with a CS degree or who've been in the industry longer.

So why did I learn TypeScript, even when I felt that way? Truthfully, TypeScript is becoming more and more of a required skill set in the job market. Most, if not all, companies are now adopting TypeScript in their codebases. It's the way the industry is moving, so why would I stand still?

What is TypeScript

TypeScript is a superset of JavaScript that adds optional static typing to the language. It was created by Microsoft and is open source, which means that anybody can use it and contribute to its growth. TypeScript is frequently used for large-scale JavaScript applications because it aids in the detection of problems before they become runtime faults, which can be difficult to debug. Basically, TypeScript is like having strict parents who never let you do anything until you have their approval.

Benefits of TypeScript

  • Type checking: You can declare types for variables, functions, and components in TypeScript. This aids in the detection of mistakes early in the development process, before they generate runtime errors.

  • Increased code maintainability: Because TypeScript provides improved type checking, it can help make your code more self-documenting and easier to maintain in the long run.

  • Improved IDE integration: Many major IDEs, like Visual Studio Code, have good TypeScript support, including autocompletion and type verification. This can help to accelerate your development process and detect issues before they arise.

  • Increased scalability: When your app increases in size and complexity, TypeScript may assist you in managing that complexity by making it easier to reason about your code and detect mistakes early.

Embracing TypeScript

Finding great and up-to-date learning resources for TypeScript is very simple. Even the official TypeScript docs are so well written and easy to follow. Although the best way to learn any programming language is by reading the docs, I opted to use the Scrimba learning platform as my starting point. The TypeScript course by Ania Kubรณw was exactly what I needed. The main reason I love Scrimba is not only how instructors explain and teach in a simple and understandable manner, but also because you learn by doing! It's just better for overall confidence building and muscle memory.

Not to forget, the overall best way to learn a new language is to build a project.

And that I did!

Setting up Typescript React

Deciding what to build to put my TypeScript knowledge into practise didn't take long. I've always known that I would love to build out a fansite for my favourite singer, Lorde, just like I did for Coldplay.

Setting up my React app with TypeScript was a straightforward process. I followed the guide from the TypeScript React CheatSheet, which also contains VS Code extension suggestions, starter kits, and video tutorials on how to set up and use Typescript in your React app.

How did I set up TypeScript with React? I just ran this line of code below, installed Tailwind CSS and began building.

npx create-react-app <app-name> --template typescript

Challenges

What's TypeScript without problems?

  1. Type is not ...assignable??? ๐Ÿ™†๐Ÿพโ€โ™€๏ธ

The "S" in TypeScript stands for "screaming!" I've never in my life been so scared of the red squiggly lines in VS Code. Even after an honest mistake, I found myself being screamed at by TypeScript. What was more challenging in this case is what to do in cases like this:

I am using Auth0 for the authentication and authorisation of my Lorde application. In my .env file, I had my domain and clientID environment variables defined, each with their respective values. In order for Auth0 to work throughout my app, I have to wrap my app component with an Auth0Provider. The problem was that when I wanted to access my environment variables, TypeScript threw an error.

TypeScript was saying to me, "I cannot give access to this environment variable to the 'clientId' variable because it might be undefined or 'non-existent" and because the 'clientId' variable only accepts strings." I won't lie; I panicked a bit. After all, it is indeed my first TypeScript React app.

As always, I've done research. I went to Stack Overflow, and thankfully, someone else had the exact same problem. Really, I love you people of Stack Overflow, especially those who offer solutions in the discussions ๐Ÿ˜‚. I learned of the non-null assertion operator (!) in TypeScript. What that does is that it takes a typed variable and removes the "undefined" and "null" types from it. This is me telling TypeScript that the values of environment variables will never be null or undefined. Gladly, that solved the problem.

  1. Property is ...missing??? ๐Ÿ‘€

One debugging lesson I always learn after successfully debugging a problem but fail to apply at times is, "REST!" Really, resting! You can be so surprised at how quickly you can debug your code after a good break from the keyboard.

Going back to this issue, in TypeScript, you need to define the structure of your objects. Objects have types, too. You can do so in three ways: they can be anonymous, named using interfaces, or type aliases. In my case, I used a type alias.

Also, take note that one of my properties is marked as optional by adding a question mark (?) to the end of its name. The albumArt3D is set to optional in case the link to the album art is not provided. TypeScript even recognises that this property may potentially be undefined.

The error given to me this time is that the JSON data from "AlbumsData" (which is an array of objects) cannot be assigned to the "albums" props from the "AlbumsContent" component. meaning that the property types of AlbumsData and albums do not match!

Solution? Well, there are two. 1) I took a break! 2) it was a spelling mistake! That's it. All those 2 hours of figuring out if I'm the problem, if the code is not the problem, or if I should throw in the towel, quit, and be a farmer were the result of a spelling mistake. The "popularAlbumTrack" property of "AlbumsData" (JSON) does not match the "popularalbumTrack" property found in "albums" props. I fixed that problem by capitalising the "A."

Another lesson that keeps proving to be true is to take time to read the error messages. Whether in the terminal, in the browser console, or in this case, hovering over those wavy red lines Reading these error messages has helped me with understanding the problem I'm dealing with and its source, as well as with effective error handling and troubleshooting.

  1. Unique title ...huh? ๐Ÿ’

This one wasn't really scary, but it was worrying regardless. One thing about me is that the code may run, but if I have these yellow squiggly lines anywhere in my code, I'd like to get rid of them. So how did I rid myself of this issue?

The warning, should I say, suggests that the "iframe" element must have a unique title property. Solution? I added a title within the iframe element, and for the unique title, I passed in the albumTitle prop as the title of the iframe. Like so:title={albums.albumTitle} and development went on ahead, happily! No yellow squiggly lines!

Lessons Learned

The purpose of this project was not only to practise my typescript but also my react.

On the TypeScript side of things, I wanted to learn how to assign types to my variables, functions, and React components. How to define object types using type aliases, how to set optional properties in objects, how to write functional components with TypeScript, how to use the union type, the non-null assertion operator, and how to build a React app with TypeScript.

On the React side, learning how to separate logical and UI components in my application Setting up and using local JSON to render on my app, implementing user authentication and authorization, practising my react router knowledge, learning how to conditionally render components once the user is signed in or not, defining children props so to build a protected routes wrapper component and wrap it around my routes, and only allowing authenticated users to access those routes

Also, I wanted to practise my grid skills with Tailwind CSS, as you can probably tell from the layout.

Otherwise, what does my Lorde app include? Apart from the home page, I give a brief introduction about myself, then there's a biography page that's all about Lorde's background, then we have the albums section, which is an explanation of each album and you can listen to the previews of the albums, a gallery page of Lorde's images, and finally, a socials page of Lorde's social platforms.

What have I learned overall? TypeScript is great at catching mistakes at compile-time rather than runtime. It helps prevent issues such as "undefined" variables (as we've seen with my environment variables issue) or incorrect data types from causing runtime errors.

What I also love about TypeScript is that it provides better support for tooling and debuggers, as they use the "type" information to give more accurate and helpful suggestions and feedback, making the code easier to maintain and debug!

Learn TypeScript

After reading my personal experience and perhaps learning from the experiences of others, do you now consider adding TypeScript to your tech stack? No? Perhaps? Not convinced? That's okay. Each one to their own will.

If you'd like to explore TypeScript and add it to your projects, fear not, for there are a lot of great tutorials available and many libraries (respective of each framework) have TypeScript support. Starting off with the official docs, I promise you that the documents are just so good, well explained, and straight to the point.

Into articles? Many articles can be found, but my favourite is getting started with TypeScript + React from the DEV community. Into videos? You can use this search query: React TypeScipt Tutorial on YouTube and/or follow this amazing TypeScript Full Course for Beginners | Complete All-in-One Tutorial | 8 Hours course by Dave Grey.

Other resources include a TS course from the tutorial's teacher and SaltyCrane's TypeScript React cheatsheet. Once you're done with your learning (let's be honest, you can never be done learning as a developer) and you're ready to test your TypeScript knowledge, why not test it on the TS playground!

Closing

We've reached the end of the article but also the beginning of my TypeScript journey, and perhaps yours too.

I've shared my insights on why I was afraid to learn it in the first place, what TypeScript is and its benefits, setting up my project, the challenges I've faced, the lessons I've learned, and how you can get started as well.

TypeScript is not as hard as I thought it would be, nor does it hinder my productivity. Instead, it makes me feel like I'm a hardcore programmer! Yep.

It's been an interesting project to build because I've honestly never thought I'd ever be comfortable building a React app without having to Google every 2 seconds. It makes me happy to see how far I've come and how I'm comfortable learning more languages to add to my tech stack.

What's next? I plan to build more TypeScript projects and to get more comfortable with it.

But before I can get started with this Emoji Builder, I have to fix the issues brought to my attention by the community on Twitter. These issues are: the image on the home page is wonky and stretches, the z-index issue on the social page on some browsers (Safari ๐Ÿคซ), and the menu closing when the user clicks outside the menu.

I hope you've enjoyed and learned a thing or two from my experience. TypeScript is worth the type ...I mean hype!

Happy learning :)

Did you find this article valuable?

Support ZordCoder by becoming a sponsor. Any amount is appreciated!

ย