How do you type props in a TypeScript React component?

clock icon

Asked 1 year ago

message icon

1

eye icon

3

I’ve recently started using TypeScript in my React project to improve type safety, and I’m trying to figure out the correct way to type props for my components. In plain JavaScript, I would just pass props and access them directly, but with TypeScript, I know I need to define types or interfaces to describe the structure of those props.

I’m unsure where exactly I should define the prop types — should I use interface or type? And how do I pass that type into the functional component? Also, if my component has children or optional props, how do I reflect that in the types?

1 Answer

Here’s how you can do it step-by-step using both interface and type (both work — it's a matter of preference, but interface is often used when describing object shapes like props):


✅ Example Using interface

1import React from 'react';
2
3interface ButtonProps {
4 label: string;
5 onClick: () => void;
6 disabled?: boolean; // Optional prop
7}
8
9const Button: React.FC<ButtonProps> = ({ label, onClick, disabled }) => {
10 return (
11 <button onClick={onClick} disabled={disabled}>
12 {label}
13 </button>
14 );
15};
16
17export default Button;
1import React from 'react';
2
3interface ButtonProps {
4 label: string;
5 onClick: () => void;
6 disabled?: boolean; // Optional prop
7}
8
9const Button: React.FC<ButtonProps> = ({ label, onClick, disabled }) => {
10 return (
11 <button onClick={onClick} disabled={disabled}>
12 {label}
13 </button>
14 );
15};
16
17export default Button;

✅ Example Using type

1type ButtonProps = {
2 label: string;
3 onClick: () => void;
4 disabled?: boolean;
5};
6
7const Button = ({ label, onClick, disabled }: ButtonProps) => {
8 return (
9 <button onClick={onClick} disabled={disabled}>
10 {label}
11 </button>
12 );
13};
1type ButtonProps = {
2 label: string;
3 onClick: () => void;
4 disabled?: boolean;
5};
6
7const Button = ({ label, onClick, disabled }: ButtonProps) => {
8 return (
9 <button onClick={onClick} disabled={disabled}>
10 {label}
11 </button>
12 );
13};

1. With children:

1interface CardProps {
2 children: React.ReactNode;
3}
4
5const Card: React.FC<CardProps> = ({ children }) => {
6 return <div className="card">{children}</div>;
7};
8
1interface CardProps {
2 children: React.ReactNode;
3}
4
5const Card: React.FC<CardProps> = ({ children }) => {
6 return <div className="card">{children}</div>;
7};
8

2. Optional Props:

1Just add ? after the prop name:
2interface Props {
3 title: string;
4 subtitle?: string; // optional
5}
6
1Just add ? after the prop name:
2interface Props {
3 title: string;
4 subtitle?: string; // optional
5}
6

1

Write your answer here

Top Questions