Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In React Typescript how to define type for ...rest parameter for native html elements?

I'm trying to filter some props and then pass down the rest of the props to a native html element like so:

const Placeholder = (
  display: boolean,
  ...rest: Array<React.LabelHTMLAttributes<HTMLLabelElement>>
) => <label {...rest} />

The problem is that this is giving me this error:

Type '{ length: number; toString(): string; toLocaleString(): string; pop(): LabelHTMLAttributes<HTMLLabelElement> | undefined; push(...items: LabelHTMLAttributes<HTMLLabelElement>[]): number; ... 28 more ...; flat<U>(this: U[][][][][][][][], depth: 7): U[]; flat<U>(this: U[][][][][][][], depth: 6): U[]; flat<U>(this: U[]...' has no properties in common with type 'DetailedHTMLProps<LabelHTMLAttributes<HTMLLabelElement>, HTMLLabelElement>'.ts(2559)

How would I define the types for the ...rest parameters for a native html element like a label in Typescript / React?

like image 323
Tom Avatar asked Apr 29 '26 06:04

Tom


1 Answers

The type of label is: React.DetailedHTMLProps<React.LabelHTMLAttributes<HTMLLabelElement>, HTMLLabelElement>

So relying on this, something like this should work:

interface Props
  extends React.DetailedHTMLProps<
    React.LabelHTMLAttributes<HTMLLabelElement>,
    HTMLLabelElement
  > {
  display: boolean;
}

const Placeholder = ({ display, ...rest }: Props) => <label {...rest} />;

const App = () => <Placeholder display htmlFor="form" />;

Also, note that since the first argument is props is being destructured as an object (so ...rest is the remaining props as an object), not as an array.

like image 85
skovy Avatar answered May 01 '26 21:05

skovy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!