Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

307
Views
TypeScript + React: How do I type a `rest` props that collects the rest of the props into an object and later spread them to some element?
function Foo({
  children,
  ...rest
}: {
  children: React.ReactNode;
  /*rest: how do I type `rest`? */
}) {
  return (
    <span style={{ background: "red" }} {...rest}>
      {children}
    </span>
  );
}

export default function App() {
  return (
    <div className="App">
      <Foo style={{ background: "blue" }}>Hello CodeSandbox</Foo>
    </div>
  );
}

Here is the demo: https://codesandbox.io/s/how-to-type-rest-huv2z?file=/src/App.tsx:50-412

Foo is used to override the props that span accepts. How do I type rest in Foo?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You can't type the spread portion of the object directly, but you can add the necessary properties with the union type (&).

In this case, the extra properties you want to allow are of type React.HTMLAttributes<HTMLSpanElement>. So you end up with:

function Foo({
  children,
  ...rest
}: {
  children: React.ReactNode;
} & React.HTMLAttributes<HTMLSpanElement>) {
  return (
    <span style={{ background: "red" }} {...rest}>
      {children}
    </span>
  );
}

As an aside, you can avoid manually typing the children property using the React.FunctionComponent type. This actually avoids the union definition and is a bit more idiomatic in React code.

const Foo: React.FunctionComponent<React.HTMLAttributes<HTMLSpanElement>> = ({
  children,
  ...rest
}) => {
  // ...
}
about 4 years ago · Juan Pablo Isaza Report

0

You can use something like this as a type:

{
  children: React.ReactNode;
  /*rest: how do I type `rest`? */
} & HTMLProps<HTMLSpanElement>
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!