Home > Enterprise >  Typescript not recognizing checks from function
Typescript not recognizing checks from function

Time:08-19

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

CodePudding user response:

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 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

  • Related