Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Spread arguments with React and TypeScript

I’m moving towards using TypeScript into my application, and I have come to the point where I need to define this:

{ id, label, type, styles, ...props }

in a component like this one:

const TestComponent = ({ id, label, type, styles, ...props }): React.ReactElement => {};

How should I define the ...props part, knowing that the id is a number, label is a string, type is a string, styles is React.CSSProperties?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In order to use Types for component props, you need to declare a type and pass it to the component as a generic. If you want to code it cleaner, you can create a type.d.ts file.
You don’t need to import the type

import { FC, CssProperties } from 'react';

type Props = {
  id: number
  label: string
  type: string
  styles: CssProperties
  props: any
}

const TestComponent: FC<Props> = ({ id, label, type, styles, ...props }: Props) => {
  return ( ... )
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading