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

351
Visualizações
How to type link prop in component (React + TypeScript)?

I'm fairly new to TypeScript and I've been struggling with this for a bit now.

I would like to pass on routes to a component as a prop, but I don't know how to type it, so I keep getting TypeErrors from TypeScript.

ParentComponent (where I pass on the routes):

import { ChildComponent } from '../components';

export const ParentComponent = () => (
  
  <div>
    ...
    <ChildComponent to={"/page_one"}>text</ChildComponent>
    <ChildComponent to={"/page_two"}>text</ChildComponent>
    <ChildComponent to={"/page_three"}>text</ChildComponent>
    ...
  </div>
)

And then my child component looks like this:


  import { Link } from 'react-router-dom';

  interface ChildProps {
  children: React.ReactNode
  to?: React.LocationDescriptor<any> 
  }

  export const ChildComponent = ({children, to}): ChildProps => {
   
    ...
    <Link to={to}/>
    {children}
    ...

  }

I keep getting the Error: "... is not assignable to type 'LocationDescriptor | ((location: Location) => LocationDescriptor)'."

I have tried multiple ways to type it and have searched around, but couldn't find any solution that worked for me.

So, what's the correct way to type the 'to' prop?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

As far as I know keeping the type as string would solve the matter

type Props = { to: string; };

Also remove the question mark to make sure that the value is always passed. For some reason if the value you might get can be undefined, add a check or default value to it.

Hope this answers your query.

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