skip to Main Content

I was working with Typescript and got confused with how the compiler infers the return types differently for these two functions.

//this is of type () => boolean | ""
const isFormValid = () => {
  return jobTitle && jobTitle!=''
}

//this is of type () => boolean
const isFormInvalid = () => {
  return !jobTitle || jobTitle===''
} 

Yes, jobTitle is a string, but shouldn’t both of these be of return type () => boolean?

3

Answers


  1. isFormValid('') === '' // true
    

    If you want boolean as returned value use double !:

    const isFormValid = () => {
      return !!jobTitle && jobTitle!=''
    }
    
    Login or Signup to reply.
  2. a && b returns a if it’s "falsy". 0, null, undefined and the empty string are all "falsy".

    Login or Signup to reply.
  3. It is expected behavior. For explanation, let’s start with || operator.
    || takes the value on the right side if the value on the left is falsy.

    const value = false || 0 // 0
    const value2 = true || 0 // true
    

    The "" is also considered a falsy value:

    const value3 = "" || "str" // "str"
    

    With the &&, it assigns the left value if it is falsy, otherwise the right one:

    const value1 = false && "str" // false;
    const value2 = true && "str"  // str;
    

    Since jobTitle is a string it can be "" as well and compiler infers the two possible return values:

    1. When jobTitle is "": ""
    2. When jobTitle is not "": jobTitle === '' boolean
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search