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
If you want boolean as returned value use double
!
:a && b
returnsa
if it’s "falsy".0
,null
,undefined
and the empty string are all "falsy".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.The
""
is also considered a falsy value:With the
&&
, it assigns the left value if it is falsy, otherwise the right one:Since
jobTitle
is astring
it can be""
as well and compiler infers the two possible return values:jobTitle
is""
:""
jobTitle
is not""
:jobTitle === ''
boolean