3

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?

1
  • try Array<React.LabelHTMLAttributes<T>> Commented Sep 24, 2019 at 19:51

1 Answer 1

10

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Excellent. I frequently find myself on a quest to discover types like these.. how did you know exactly which types to use without a lot of trial and error?
Using Codesandbox or VSCode, hovering over the label in <label {...rest} /> will show you the types. Additionally, cmd + click on label (on macOS in VSCode) will open the type definitions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.