Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript: Define type that can be bool or null

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?

like image 845
shal Avatar asked Mar 01 '17 13:03

shal


People also ask

How do you define a Boolean type in TypeScript?

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.

Can boolean be null in TypeScript?

You can assign true , false and undefined and null to boolean in TypeScript without strict null checks.

Can any be null TypeScript?

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.


1 Answers

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

like image 99
Bruno Grieder Avatar answered Sep 28 '22 18:09

Bruno Grieder