Back to all blogposts

Practical code examples of why Typescript is the best choice for frontend

Grzegorz Kubiak

Grzegorz Kubiak

Frontend Developer

In my previous article: “Why use TypeScript” I discussed why Typescript is the best way to write frontend in 2021 in a very understandable way, even to non-technical people. If you weren’t happy with the lack of code in my previous article, buckle up, because we’re up for a ride!  Now it’s time to take a look at some practical examples.

React + MUI + Typescript = <3

In this blog post, I will go through some code snippets based on React, which is the most popular and widely used frontend library at this moment. Sources? Check out our analysis of two reports:

Additionally, I used here MaterialUI library for React. I know I’m discussing only React code examples here, but I believe that this is additional proof that Typescript is the best choice even for other frameworks. Think Vue (especially Vue3) or Angular. 

Without further ado, let’s go to the first example of why Typescript is the best.

Example no. 1: Generic reusable list with render props

Lists are one of the most common things that exist in frontend applications. You can see them everywhere online, e.g. list of posts on Facebook, list of files in Google Drive, list of articles on our TSH blog… 🙂 

If you’re building some bigger frontend application, you will need to render the same looking list in different places that differ only by the content inside the list item. You have to build a frontend for the university library with a reusable component for the grid list. The component needs to be the only place with styles definition, and when you’ll have to change anything in future, this will apply to all of your lists across the whole application. Let’s prepare some students and books example data.

Students’ example data:

Books example data:

Notice that these two types differ from each other (and probably there will be other data types when implementing other lists, e.g. authors, categories). You could create two separate components for each list that loops through all items, and it would probably work fine. But let’s try to use Typescript generics and React render props pattern to achieve one component reusable across the whole project where we can pass lists of any items and only define how a single grid tile should look like.

Check out the code below:

OK, so what happened here? Let’s investigate this example step by step.

First, define BaseListItem type which contains id only


This is the type that I used to define all required properties which should exist in every item passed to our list. Unique id for every database record is just standard so for sure we will have it here. This id property will also serve us to be the key of each list item.

The next thing is the GridListProps type for your grid list component props

Now things are getting more interesting. 🤔 Here you can see that I used Typescript generics functionality. It may seem scary for someone who hasn’t worked with generics before but let me explain what happens here. 

This is the generic type where I defined that whatever type will be passed here, it must contain id property because it extends my previously created BaseListItem type. This type contains two properties: items – an array of whatever type is passed to this generic, and renderItem – a function that returns ReactNode (so probably some other component or JSX).

Pro tip about TypeScript generics

Use descriptive names for Typescript generics. If you worked with generics, you’ve probably seen that many libraries use generic names like T, P, R, U etc. Of course, it’s shorter than any meaningful name, but trust me, your colleagues will thank you for naming convention understandably, even at first glance.

I even prepared a meme to convince you that single character generics are a bad idea!

Lastly, define generic functional component GridList


As you can see here, I destructured items and renderItem props. This component loops through all items and calls renderItem function with the item as an argument.

Now with component prepared like this, you can reuse it with your previous prepared mock data like this:

Students List Component

Books List Component

And in your app, you can render these lists like this: 

why typescript gif

You can reuse the same component for any list you can imagine. And achieve the following benefits:

  • The same look of every list built with this component. You only define how the content of the grid item should look like,
  • Full Typescript code autocompletion support for any kind of objects,
  • Assurance that every list item has an id property which is also key for this list item which is important for list elements identity in React.

 

Pro tip:

In StudentsList and BooksList components I explicitly provided type. Remember that you don’t have to do this because Typescript can infer the generic type based on items you passed. As seen in the gif below.

why typescript gif 2

💡 More Typescript? No problem, check this out:

Example no. 2: Custom button with conditional props and union types

Component props are used daily by frontend developers. Depending on a particular component, there can be a few or even a few hundred of them. Would you like to ensure that if you pass property X, so property Y should also be provided? Can be done with Typescript as well. Take a look at the example below. 

You want to create a custom button that has optional rounded corners. When you choose a rounded prop, then radius prop should be required. It can be achieved like this.

Ok, so what happened here? Let’s first take a look at these types:

First, define the RectangularButton type 

It’s nothing fancy, just a “regular” button. As you can see, I used two optional properties (marked by a question mark) and I defined that they are a never type. But what does never mean exactly? It’s pretty self-explanatory. Never basically means that this property cannot exist or cannot be set at all. 

Then define RoundedButton type

These are props for your rounded button. I set rounded property not to boolean but to the exact true value. It means that this property can only be true in this type. Additionally, it’s required in this case. 

Finally, create CustomButtonProps type 

I used Typescript types intersection with union types. Can you see similarities with logical operators? Because this is how it works. 

CustomButtonProps type should have all MaterialUI ButtonProps AND and properties of one of the two types: RectangularButton OR RoundedButton

So your button can have only these “shapes”:

  • ButtonProps + RectangularButton
  • ButtonProps + RoundedButton

Styles 

I created a separate type for my useStyles function.

One thing that may look strange is this Pick type, one of the Utility types from Typescript. If you have never worked with utility types before, you should check this out because they can make your life easier. Pick just creates a new type by picking some properties from the chosen type (you can pick more than one property). In our case, we just create a type that contains only a radius property. 

Pro tip: 

Of course, you could create a new type here providing explicitly radius prop and its type but Pick is better because:

  • by using Pick you don’t repeat yourself (DRY principle),
  • you have a single source of truth for your types. In the future, if you change anything in base type you won’t have to do this in all other places.

As you can see here, I used the default makeStyles approach from MaterialUI library which is also a generic function.:) It’s proof that with the generic approach and properly defined types code autocompletion works flawlessly. Imagine if you had multiple properties here. This kind of feature makes things far easier to work with.

MUI makeStyles code autocompletion

Component function definition

Let’s have a look at these few lines:

If you work with React these few lines should be self-explanatory. It’s just a functional component that returns your Button with some styles and our Button props.

As you can see with just a few lines of code we touched many helpful Typescript features and now you have a nice code autocompletion and properties restriction as you can see in the gif below:

why typescript gif 3

Now with a component prepared like this, you can use it wherever you want.

I added some inline styling to make some space between buttons

Pro tip: 

You could probably think that rounded property is unnecessary and we can achieve similar results with just one optional radius property in our type. This is true, but I wanted to show you how you can combine types that depend on each other in this example.

Why Typescript is the best frontend language? 

Summarizing our quick yet mysterious journey across React with the Typescript world you can see with just these two simple examples that Typescript gives you really powerful tools to use in your daily work. With Typescript, you gain full control over creating what you want from A to Z. 

We’ve gone through a bunch of Typescript features like creating custom types, generics, union types, intersections, types inference but there are many more things to discover. But I bet you wouldn’t stay here for another hour. 😀 

Nevertheless, if you are interested in why Typescript I encourage you to check out its official documentation. Inside you’ll find more examples and use cases of all features that will help you build the app of your dreams. I hope now you are fully convinced why Typescript is the best choice to write frontend applications. Especially with React. 💙

Trying to stay up-to-date? TechKeeper's Guide will save you a lot of time

We know how much effort it takes not to fall behind with new technologies. Our newsletter means hand-picked and condensed news in your inbox, once every two weeks. You will never miss anything big from the IT world for sure. 📰

You may also like

What do you want to achieve?





    You can upload a file (optional)

    Upload file

    File should be .pdf, .doc, .docx, .rtf, .jpg, .jpeg, .png format, max size 5 MB

    Uploaded
    0 % of

    or contact us directly at [email protected]

    This site is protected by reCAPTCHA and the Google
    Privacy Policy and Terms of Service apply.

    Thanks

    Thank you!

    Your message has been sent. We’ll get back to you in 24 hours.

    Back to page
    24h

    We’ll get back to you in 24 hours

    to get to know each other and address your needs as quick as possible.

    Strategy

    We'll work together on possible scenarios

    for the software development strategy in sync with your goals.

    Strategy

    We’ll turn the strategy into an actionable plan

    and provide you with experienced development teams to execute it.

    Our work was featured in:

    Tech Crunch
    Forbes
    Business Insider

    Aplikujesz do

    The Software House

    Copied Tekst skopiowany!

    Nie zapomnij dodać klauzuli:

    Kopiuj do schowka

    Jakie będą kolejne kroki?

    Phone

    Rozmowa telefoniczna

    Krótka rozmowa o twoim doświadczeniu,
    umiejętnościach i oczekiwaniach.

    Test task

    Zadanie testowe

    Praktyczne zadanie sprawdzające dokładnie
    poziom twoich umiejętności.

    Meeting

    Spotkanie w biurze

    Rozmowa w biurze The Software House,
    pozwalająca nam się lepiej poznać.

    Response 200

    Response 200

    Ostateczna odpowiedź i propozycja
    finansowa (w ciągu kilku dni od spotkania).

    spinner