How to add types for rest props in React and TypeScript?

Sometimes, we want to add types for rest props in React and TypeScript.

In this article, we’ll look at how to add types for rest props in React and TypeScript.

How to add types for rest props in React and TypeScript?

To add types for rest props in React and TypeScript, we can add an index signature into the prop’s type.

For instance, we write

type Props = {
  id: number;
  name: string;
  [x: string]: any;
};

const MyComponent: React.FC<Props> = (props) => {
  //...
};

to add the Props type that has the

[x: string]: any;

index signature that lets us allow any property in props.

Then we can access any property in addition to id and name without errors.

Conclusion

To add types for rest props in React and TypeScript, we can add an index signature into the prop’s type.