Full Stack Developer, Tech Geek, Audiophile, Cinephile, and Lifetime Learner!

Best Practices for Checking PropTypes in React Components using TypeScript

B

JavaScript functions that return React elements are known as React components. These are the parameters that govern what will be added to the DOM. In addition, react components, like functions, may receive props as arguments, resulting in dynamically returned items.

Props can be of any data type, although component data types may differ. Component A, for example, may anticipate a name argument with a text data type, but component B may anticipate an age argument with a numeric data type. Likewise, D may anticipate an onClick argument with a Function data type, but C may expect a post parameter with an object data type with characteristics like title and date.

How can we tell our component what kind of data it should expect?

This may be done in various methods, but this post will focus on PropTypes and TypeScript. Despite holding identical goals, these two techniques operate in different ways. So we’ll go through what these tools are, how to use them, and tell them apart before trying more advanced techniques.

Prior knowledge of PropTypes and TypeScript is necessary for a thorough understanding of this article. You’ll also require an integrated development environment (IDE), such as Visual Studio Code.

PropTypes

PropTypes is a type-checking tool for props in React apps that can be used at runtime. The PropTypes efficiency has been provided through the prop-types package since React 15.5. PropTypes let you specify the props that are expected in a component, such as whether they are mandatory or optional. You’ll get a warning in the browser’s JavaScript console if you provide a different type to an element or miss a required prop:

import React from 'react'
import PropTypes from 'prop-types'

const NotificationCard = ({ message, type, id }) => { 
  return <span>Notification</Notification>
}

NotificationCard.propTypes = {
  message: PropTypes.string.isRequired,
  type: PropTypes.oneOf(["error", "warning", "success"]),
  id: PropTypes.string.isRequired
}

export default NotificationCard

IntelliSense will provide an auto-completed prop name with the anticipated kind of data for the prop as you enter if you have to React plugins installed. Consider the following scenario:

intellisense-auto-complete-prop-name

What happens if we pass a data type that isn’t expected? What if we don’t have a needed prop?

There are no problems or warnings in the IDE. Let’s try executing the code now:

The message prop has an unexpected data type due to a wrong data type being sent, as shown in the browser console snapshot. You’ll get another error if you send a string to a message, stating that id, a necessary argument, was not given.

Warnings are only produced during development and are not provided by PropTypes in production applications. Therefore, the console will not output any warnings if an unexpected type is received when using the production version of your application.

TypeScript

When you use TypeScript with React, you may add typings to your properties that are checked at compilation time. Then, because the browser knows JavaScript, TypeScript compiles back to it.

You may need to provide the appropriate dependencies and parameters before utilizing TypeScript in your React application. If you’re using Create-React-App, for example, you may use this guide to add TypeScript support to your current app.

The following is TypeScript’s interpretation of the PropTypes definition:

import React from 'react'
import PropTypes from 'prop-types'

type Props = {
  message: string;
  type: "error" | "warning" | "success";
  id: string;
}


const NotificationCard = ({ message, type, id }: Props) => { 
  return <span>Notification</span>
}


export default NotificationCard

When you use the TypeScript IDE tools, you’ll get immediate IntelliSense warnings in your IDE whenever you supply an unexpected prop. Let’s put this to the test by entering the erroneous data type; we’ll get the following message:

We’ll get this indication if we give the right data type for message:

IntelliSense also offers further information about the mistake, as seen above, to assist you in resolving it.

When a props requirement is violated in TypeScript, the command npm run build will fail.

Add Comment

  |     |  
Full Stack Developer, Tech Geek, Audiophile, Cinephile, and Lifetime Learner!

About me

A profound honest Full Stack Developer with a passion for creating delicate solutions in the least amount of time, with more than seven years of experience in the Web Application Development. Implemented complex user stories that make the business count on more conversion and grow with it.

Started career with ASP.NET but eventually revamped skills with JavaScript, ReactJs, NodeJs and Ruby on Rails.

Throughout my career, I have contributed to the businesses who have a positive impact on society through my active and innovative contributions to the growth of the organisation. While being an independently motivated engineer, I appreciate the collective efforts and collaborative productivity within the team environment. I am open-minded and focused on learning new technologies which have direct impacts on the betterment of human lives.