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

233
Visualizações
Typescript check if a value is string

I have a component:

export type IDAta = string | number | null;

interface IDAta {
  data?: string | number | null;
  verify: boolean;
}

const App: React.FC<IDAta> = ({
  data = '',
  verify = true,
}) => {

  if ((data || data === 0) {
    return (
      <div>
        {verify && isText(data) ? (
          <Child text={data} />
        ) : (
          data
        )}
      </div>
    );
  }

};

export default App;

isText and Child component expect the parameters only to be string, but doing this verify && isText(data) then i get error in typescript like Type 'number' is not assignable to type 'string'. . This could be solved as follow:

{
  verify && typeof data === 'string' && isText(data) ? ( 
  <Child text = {data as string}/>
  ) : (
    data
  )
}

I am not sure if this solution is ok, because typeof data === 'string' double the logic from isText function which looks like this:

const isText = (data: string) => {
  return typeof data === 'string';
};

Question: What will be the best solution to solve the issue described above?

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

0

A type guard/predicate function:

function isText(data: any): data is string {
  return typeof data === 'string';
};
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