TypeScript Tutorial
TypeScript Booleans
boolean is true or false. Comparisons produce booleans. Conditions consume them.
true or false
A boolean stores one of two values: true or false. That is the whole type. You use it to remember a yes-or-no fact: a door is open, a score is high enough, a loop should keep going.
Write the literals in lowercase. True and False are Python. TypeScript will not compile them unless you declared names with those spellings — and you should not.
A complete program
Declare a boolean, print it, then print a comparison. console.log prints the wordstrue and false, not 1 and 0 the way C++ coutoften does.
Example
const ready: boolean = true;
const empty: boolean = false;
console.log(ready);
console.log(empty);
console.log(7 > 3);
console.log(7 === 3);Run this in /typescript/try with Try it in TypeScript. You should see true, false, true, false.
Comparisons produce booleans
Every comparison expression has type boolean. You can store it, print it, or pass it straight intoif. Prefer === for equality, as in the Operators chapter.
| Expression | True when |
|---|---|
a === b | a equals b (same type and value) |
a !== b | a is not equal to b |
a < b | a is less than b |
a <= b | a is less than or equal to b |
a > b | a is greater than b |
a >= b | a is greater than or equal to b |
Use === to compare. A single = assigns. Writing if (x = 1) is a type error in TypeScript when x is a number, because the assignment is not aboolean. That protection is one reason the type is worth writing.
Combine with and, or, not
TypeScript uses && (and), || (or), and ! (not).&& is true only if both sides are true. || is true if at least one side is true. ! flips a value.
Example
const age: number = 20;
const member: boolean = true;
console.log(age >= 18 && member);
console.log(age < 18 || member);
console.log(!member);Store a comparison
You do not have to print a comparison immediately. Put it in a boolean variable and reuse the name. Change age and compile again to see the stored value flip.
Example
const age: number = 20;
const adult: boolean = age >= 18;
console.log(adult);
console.log(adult === true);Conditions consume them
An if, a while, and the middle part of a for all expect something that converts to boolean. You will write that in the next chapters. The value itself is still just true or false.
Example
const ready: boolean = true;
if (ready) {
console.log("go");
} else {
console.log("wait");
}Other values convert too: 0, "", null, and undefined are treated as false in a condition. Prefer an actual boolean or a comparison so the intent is obvious.
What to remember
booleanholdstrueorfalse.- Comparisons such as
===and<produce a boolean. console.logprints the words true and false.- Combine tests with
&&,||, and!.
Next: if and else — the first place those booleans get used.