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

199
Vistas
Typescript not recognizing checks from function

I have a function that validates input

export const isValidString = (value: string | null | undefined): boolean => {
  return value != null && value.length > 0 && value.trim() != "";
};

const func = (input: string) =>{
  // some code
}

const someFunction = (input : string | null | undefined) => {
   if(isValidString(input)){
     func(input); //This is the line that is complaining
  }
};

the call to the func is throwing an error which I'm not sure why as the isValidString is making sure the input is not undefined. Any reason why ?

Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
Type 'undefined' is not assignable to type 'string'.ts(2345)

However, if I just do

if(input != null) func(input);

Everything works

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

When isValidString() only returns a boolean, typescript does not know that you have checked that your type is a string now.

E.g. when you hoover over the input variable in this typescript playground example, you can see that the type is still string | undefined | null enter image description here

To change that, your function must be a type-guard

export const isValidString = (value: string | null | undefined): value is string => {

Note, the return type of the function is now value is string

When you hoover over input in the new example, you can see that the type is now 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