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,
undefinedand
null` (when not using strictNullChecks):
If we use strictNullChecks
, the only values we cann asign are true
and false
.
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.
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)
Holy $hit you cannot assign
null
to a variable.Good work! Pretty nice how you put all your learnings in this short-form posts. Keep it up!