Cover image for Boolean type in Typescript - simple explanation

Boolean type in Typescript - simple explanation

ari_o profile image Arika O ・1 min read

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


Editor guide
abhigya53544714 profile image
Abhigyan Kumar

Holy $hit you cannot assign null to a variable.

caroso1222 profile image
Carlos Roso

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