Summary: in this tutorial, you will learn about the TypeScript boolean
data type and how to use the boolean keyword.
The TypeScript boolean
type has two values: true
and false
. The boolean
type is one of the primitive types in TypeScript.
In TypeScript, you can declare a boolean variable using the boolean
keyword. For example:
let pending: boolean;
pending = true;
pending = false;
Code language: JavaScript (javascript)
Boolean operator
To manipulate boolean values, you use the boolean operators. TypeScript supports common boolean operators:
Operator Meaning && Logical AND operator || Logical OR operator ! Logical NOT operatorFor example:
const pending: boolean = true;
const notPending = !pending;
console.log(result);
const hasError: boolean = false;
const completed: boolean = true;
let result = completed && hasError;
console.log(result);
result = completed || hasError;
console.log(result);
Code language: JavaScript (javascript)
Type annotations for boolean
As seen in previous examples, you can use the boolean
keyword to annotate the types for the boolean variables:
let completed: boolean = true;
Code language: JavaScript (javascript)
However, TypeScript often infers types automatically, so type annotations may not be necessary:
let completed = true;
Code language: JavaScript (javascript)
Like a variable, you can annotate boolean parameters or return the type of a function using the boolean keyword:
function changeStatus(status: boolean): boolean {
}
Code language: JavaScript (javascript)
Boolean Type
JavaScript has the Boolean
type that refers to the non-primitive boxed object. The Boolean
type has the letter B
in uppercase, which is different from the boolean
type.
It’s a good practice to avoid using the Boolean
type.
boolean
type has two values true
and false
.boolean
keyword to declare boolean variables.Boolean
type unless you have a good reason to do so.Was this tutorial helpful ?
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4