avatarDaniel Babinszky

Summary

The website content provides guidance on typing React props in TypeScript, emphasizing the importance of proper typing for better code clarity and safety.

Abstract

The article "How to type React props in TypeScript" explains the significance of props in React components and how to type them effectively using TypeScript. It begins by illustrating the basic usage of props in a React component, demonstrating how they are passed and accessed within the component. The author then criticizes the common practice of typing props as any, advocating instead for detailed object typing to ensure type safety and code understanding. The article covers the concept of optional props, the use of the ? symbol to denote optional properties, and the benefits of destructuring props for cleaner code. The author's approach allows developers to clearly define which props are required and which are not, thus avoiding runtime errors and enhancing maintainability. The article concludes with a call to action for readers to support the author and follow for future content.

Opinions

  • The author suggests that typing props as any in TypeScript is not a best practice and should be avoided.
  • They emphasize the importance of defining prop types explicitly for better code clarity and to prevent runtime errors.
  • The article promotes the use of optional properties with the ? symbol to make certain props non-mandatory during component usage.
  • Destructuring props is presented as an elegant solution for improving code readability and maintainability.
  • The author encourages readers to engage with their content and support them financially, indicating a preference for direct reader support over other monetization methods.

How to type React props in TypeScript

Props are essential in React. They can be used within, and you can provide the components a variety of values and functions. Because different props can be used as object keys in components, you can destructure and type them.

Adding props to a component is pretty simple

⚛️ ADDING PROPS:
<BlogPostComponent 
  title='First post'
  subtitle='Created by me'
/>

and this is how you use it inside

🤸‍♂️ USING THEM IN THE COMPONENT:
const BlogPostComponent = (props) => {
  return(
    <div>
      <p>{props.title}</p>
      <p>{props.subtitle}</p>
    </div>
  )
}

Let’s examine the word props in the function component’s argument more closely now. As you can see and recall, it basically equals an object, and you can refer to its values (props.title and props.subtitle) just like any other object, therefore if you use TypeScript, you can type them as well.

Typically, programmers who only use TypeScript because it’s popular type props as follows:

❌ PLEASE DON'T DO THAT
const BlogPostComponent = (props: any) => ...

We can do better than this. How about defining the object in detail? We already know the properties we want to pass, so props will be an object with a title: string and a subtitle: string field:

THIS COULD WORK 
const BlogPostComponent = (props:
  { title: string, subtitle: string }
) => ...

This is really neat. You are perfectly aware of the props and the types you must provide to the component. Let’s explore some extras now:

Optional props

Almost all of your props are optional when using React with simple JavaScript. If you miss passing one and, let’s say, only pass the title for the BlogPostComponent, nothing will go wrong.

With TypeScript and typed properties, the scenario is totally different. Once they have been entered into the component, we must state clearly which are required and which are optional. Fortunately, we have the ? symbol for optional properties, allowing us to use it in components as well.

🚩 THE SUBTITLE IS OPTIONAL
const BlogPostComponent = (props:
  { title: string, subtitle?: string }
) => ...

Here’s the component without it:

👍 YOU CAN DEFINE YOUR COMPONENT WITHOUT IT
<BlogPostComponent 
  title='Second post without a subtitle'
/>

Destructuring

💡 Allows values from arrays or properties from objects to be unpacked into separate variables.

In every example above we referred to props object keys as we should: props.title and props.subtitle. That means we want to deal with the props object’s title and subtitle fields. A more elegant way to use those fields is to destructure them in the component’s argument, and here’s how you can do it:

💃 PROPS FIELDS CAN BE USED ON THEIR OWN IF YOU DESTRUCTURE THEM
const BlogPostComponent = (
  { title, subtitle }: { title: string, subtitle?: string }
) => {
  return(
    <div>
      <p>{title}</p>
      <p>{subtitle}</p>
    </div>
  )
}

Now you can refer to the props’ values with their unique variable names.

👋 I hope you found this useful in your search for new material to learn from. Thank you for taking the time to read this!

☕️ If you understand something better from my article, you can support me by buying me a coffee: https://www.buymeacoffee.com/daanworks

📯 Subscribe to my e-mail list, and follow me here or on Twitter if you want to read more stories like this in the future!

React
Programming
Software Engineering
JavaScript
Typescript
Recommended from ReadMedium