Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

232
Vistas
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 Respuestas
Responde la pregunta

0

A type guard/predicate function:

function isText(data: any): data is string {
  return typeof data === 'string';
};
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda