Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Everything works

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading