I have a function that can return either true, false or null.
How do I define this type? For now, as a temporary solution, I define it as boolean | string
, but it's misleading, someone may thing that it really may return string... Any ideas?
TypeScript treats it like an object type. So, instead of using upper case function checkExistence(b: Boolean) , use the lower case function checkExistence(b: boolean) boolean type.
You can assign true , false and undefined and null to boolean in TypeScript without strict null checks.
Introduction to TypeScript Nullable. TypeScript Nullable is a special type null that has the value null. TypeScript Null is much like void, i.e. not useful on its own. By default, null is a subtype of all other subtypes which means a user can assign null to any of the data types like string, number, etc.
It depends on which typescript version you are using.
before 2.0 null
can be returned on ("is in the domain of") any type, so boolean
is your type
starting with 2.0, if you enable --strictNullChecks
then you have to specify that a type can return null
. So your type will be boolean | null
More details here paragraph Non-nullable Types
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With