Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

197
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!