React Prop Types in Typescript

javascript react programming

Everything must have a type in typescript. Let’s see how this would work for React props.

There’s three ways to accomplish this:

  1. using the prop-types library
  2. using typescript interfaces
  3. using Reacts React.FC built-in type

The prop-types library

# install the library
npm install prop-types
// import the library
import PropTypes from 'prop-types'

function MyComponent({ number, children }) {
    return (
        { number }
        { children }
    )
}

// Add this after your component
MyComponent.propTypes = {
    number: number,
    children PropTypes.element,
}

Using typescript interfaces

interface Props {
    number: number,
    children: JSX.Element[] | JSX.Element,
}

function MyComponent({ number, children }: Props) {
    return (
        { number }
        { children }
    )
}

React.FC (function component)

const MyComponent: React.FC<{ number: number }> = ({ number }) => {
    return (
        { number }
    )
}