DEV Community

Cover image for Boolean type in Typescript - simple explanation
Arika O
Arika O

Posted on • Updated on

Boolean type in Typescript - simple explanation

The most basic datatype is the simple true/false value, which JavaScript and TypeScript call a boolean value. In Typescript, we can assign four values to it, and thise are true, 'false,undefinedandnull` (when not using strictNullChecks):

Alt Text

If we use strictNullChecks, the only values we cann asign are true and false.

Alt Text

When using variables that work with boolean, I like to name them something from which we can infer we are dealing with this type - like in this case, using the word is in isLoggedIn (it can be yes -> true or no -> false). You can name them however you want, this is just a personal preference and I've seen quite a few people doing it. Try to store something different inside them, and again we get an error.

Alt Text

This type is super useful when it comes to controlling the flow of a program using conditional statements (if this is true, do that, if this if false, do that). I don't use it much with pure Javascript but since I am working with React, it comes in handy when trying to render things based on different conditions. Or, in conjunction with interfaces, I can make sure that the props I'm trying to pass to a component are the correct type, in this case, boolean.

Image source: Christina Morillo/ @divinetechygirl on Pexels

Top comments (2)

Collapse
 
spez profile image
Abhigyan

Holy $hit you cannot assign null to a variable.

Collapse
 
caroso1222 profile image
Carlos Roso

Good work! Pretty nice how you put all your learnings in this short-form posts. Keep it up!