kyrolos magdy
kyrolos magdy

Reputation: 393

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?

Upvotes: 0

Views: 191

Answers (1)

Amini
Amini

Reputation: 1792

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 ( ... )
}

Upvotes: 1

Related Questions