简体   繁体   中英

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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM