Typescript Vs. PropTypes: A Comprehensive Comparison

Typescript Vs. PropTypes: A Comprehensive Comparison

As your application gets bigger, the chance of having more bugs increases, and knowing that you can catch them easily through type-checking is a great thing. With PropTypes and TypeScript, whether you are writing, reading, or maintaining a codebase, the components will always be predictable for you. This article is not to discredit one over another; it is mainly to point out where you would should use TypeScript over PropTypes and point out use cases where you would need to use both in your code for best performance. We will be looking at PropTypes and TypeScript for React Applications.

I know using both might come with some form of resistance as it would mean more lines of code and more time spent on a project but think of the benefits that would come from having to put in that extra effort.

Let’s get to it

What Is PropTypes?

PropTypes is a React module library used for type checking of props. PropTypes are a technique to ensure that components utilize the proper data type, pass the correct data, use the right kind of props, and receive the correct type of props from other components. With PropTypes, when you enter incorrect data into a component it detects the issue and alerts you at Runtime.

(Runtime Time means execution time.)

PropTypes is a tool that lets you validate the structure and type of all your props, if there are any issues they show up as errors in the console of your browser dev tools.

How To Specify/Use PropTypes In Your Application

Before React v15.5 and above, to use PropTypes we had to call React.PropTypes; its utility was available as part of the React package; it provided a lot of validators for configuring type definitions. However, in later versions of React, this utility has been moved to a separate module called prop-types. Now you need to add prop-types as a dependency for your project:

npm install prop-types --save

Then import it into your project files:

import PropTypes from 'prop-types';

To learn more about using prop-types and its differences from using React.PropTypes, check out the official prop-types documentation. It doesn't matter if you are working with a class or function component; setting up PropTypes works the same. You only need to define the PropType property object that outlines the props for the component.

//class component 

import PropTypes from 'prop-types'

class Component {

Component.propTypes = {
  // Add props here
}

export default Component



//function component

import PropTypes from 'prop-types'

function Component(props) {
  return 'Type Checking'
}

Component.propTypes = {
  // Add props here
}

export default Component

Lets take a look at this code sample

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

function AppComponent(props) {
   const {name, age, city, items} = props

   return (
       <div></div>
   )
}

AppComponent.PropTypes = {
   name: PropTypes.string.isRequired,
   age: PropTypes.number.isRequired,
   city: PropTypes.string,
   items: PropTypes.array

}

We imported PropTypes and specified the exact type checks we need in the AppComponent. The name properties accept a value of a string. The isRequired attribute shows that the name property must be included, likewise the age. You can use PropTypes to specify any data type.

What Is TypeScript?

TypeScript is a strongly typed language that extends JavaScript and compiles it to plain JavaScript to be used in the environments that runs JavaScript (Web, Deno, Nodejs). A superset of JavaScript used as a language and a collection of tools. Also, it is best for extensive team interactions and it is ideal since it has optional static typing, which can assist catch errors as they happen.

Static Typing means you are type-checking without the execution of code.

TypeScript tools and plugins type checks your props as static data/application.

How To Specify/Use TypeScript In Your Application

To use TypeScript in your React application, you provide the necessary dependencies and configurations. For instance, if you’re using Create React App, you can follow this documentation to add TypeScript support to your existing application. We can specify TypeScript in an application using the Type Alias or Interface.

//Type alias

import React from 'react'

type Props = {
    name: string;
    age?: number;
    city?: string;
    items: array;
}

function AppComponent(props: Props) {
    const {name, age, city, items} = props

    return (
        <div></div>
    )
}
export default App;

This is how you would specify TypeScript with Interface

import React from 'react'

interface ComponentProps{
  name?: string;
  age: number;
  location: string;
}

function App({name, age}: ComponentProps){
  return(
    <div></div>
  );
}

export default App

Similarities Between TypeScript And PropTypes

So TypeScript and PropTypes are type checkers- Obviously! While this article aims to share differences between both type checkers, it helps to point out some similarities these type checkers share.

  • Used for type-checking

  • Used during development and not production

Used for type-checking: Both are type checkers and used for type-checking props in a JavaScript-React application. They both help to ensure that the props receive the correct value types. Using both tools in your code guarantees passing the correct value, just as the component expects.

Used for development and not production: Both tools can only print and show errors in development. During production, PropType errors will not would not print to the console. TypeScript gets converted to JavaScript during production; hence it does not have type checking.

Difference Between TypeScript And PropTypes

So here are the difference we will be exploring;

  • Runtime vs Compile time

  • Syntax and semantic Highlighting

  • Advanced Features in Typescript and PropTypes

  • Required vs Optional

Note: Both Type checkers use different methods to work. This difference determines how you would prefer to use one over another based on your use case and preference. PropTypes are still relevant even in a React application using TypeScript.

1. Runtime Vs Compile Time

Type checking for prop types happens at runtime; during execution (Execution: during development). The PropTypes is checked via the browser if there is an error; it shows on the console. TypeScript checks for errors at compile time. While you are generating the JavaScript code files the browser can read- TypeScript will check for errors. Once it finds the error, the compilation process stops and yields an error.

TypeScript has no way of explicitly type-checking the exact data we receive from an external server. Let's say data from an API (unless we are getting that data on compile time (build time); this will be unsuccessful because you would only get such data during runtime).

In this case, PropTypes has the advantage; You’d use it to check if you are getting the expected data from the server.

2. Syntax And Semantic Highlighting

Both tools have support plugins; PropTypes has the Intellisence plugin that aids its auto-completion. Although, TypeScript has more support for a wide range of tools. Some tools you can use with TypeScript are EsLint, TypeScript Toolbox, and so on; These tools are listed in detail via this post. If you prefer to work with lots of tools while you code, you will lean more toward TypeScript because it has many diverse options. TypeScript also has tools that work with the various IDE that supports TypeScript, not only Visual Studio Code.

3. Advanced Features In Typescript And PropTypes (Limitation Of PropTypes For Typing Compared To Typescript )

TypeScript is not limited to the available ones React provides with PropTypes. It allows for many dynamic and advanced features; There are many ways you can specify types for your props in TypeScript that PropTypes may not be able to provide. So in the most sense, PropTypes is limited. Although PropTypes does offer Advanced type checking like;

  • Checking For Any Type

You might want to pass a prop with little regard for its type you could with PropTypes.any it will never throw a warning for the type.

Component.propTypes = { name: PropTypes.any }
  • Creating An Enum

To ensure that a prop's value is from a specific list, you can use PropTypes.oneOf() to define the allowed values.

Component.propTypes = {
  state: PropTypes.oneOf([
    'LOADING',
    'READY',
    'ERROR'
  ])
}

Others include; PropTypes.element, PropTypes.instanceOf(), PropTypes.ObjectOf(), PropTypes.OneOfType, PropTypes.arrayOf(), and a few others. These are some of the advanced type checking PropTypes allows. There are defined in the PropTypes documentation; you can not define types outside the available ones with PropTypes.

However, with TypeScript, you can freely create checks to fit any of your use cases. Some example;

  • TypeScript allows you to combine Types with Interfaces and perform conditional type checking.

  • The building of Read-Only props. Properties that you cannot reassign to other values in the component.

  • You can set up conditional props with TypeScript but not with PropTypes. It is an instance where you specify different/multiple structures of the properties object depending on another value.

A usage example of advanced type checking with TypeScript

import React from "react";
import PropTypes from "prop-types";
type Props =
    | {
            type: "pass";
            message: "You passed the test";
      }
    | {
            type: "fail";
      };

const ResultComponent = (props: Props) => {
    return <div>Result</div>;
};
export default ResultComponent;

In the above code example, if the type is pass, then a message property is also required. But if it fails, then we don’t need to specify another property.

4. Required vs Optional

With props, all options are optional by default; you have to use (isRequired) to make it required(mandatory). With Typescript, all props are required by default, so when you want them to be optional; you need to mark them with (?)

Benefits of Type Checking With TypeScript And PropTypes

  • The early detection of errors at compile time

  • A consequential gain in execution rate

  • Used for checking all execution paths

  • Faster development types

Final Thought

PropTypes and TypeScript are the subjects of some misconceptions. Some people feel one is overall better than the other, but I find both tools equally significant. This article has covered the definitions of PropTypes and TypeScript, their applications in React apps, their differences, and how they can be combined. You can create the first layer of defense for your applications by using propTypes and further strengthen your application with TypeScript. Overall, PropTypes is simpler to set up and use.