React Prop Types in Typescript
Published on July 10, 2023 javascript react programmingEverything must have a type in typescript. Let’s see how this would work for React props.
There’s three ways to accomplish this:
- using the
prop-types
library - using typescript interfaces
- 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 }
)
}