Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

314
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda