Boolean type in TypeScript is declared using boolean keyword and it can hold either true or false values.
Declaring Boolean Type in TypeScript
We can declare Boolean in TypeScript using boolean keyword and assign either true or false values. It is always good practice to add verbs with variable names like is, has etc.
// boolean declaration
let isValid : boolean ;
isValid = true ;
TypeScript uses implicit type inference to identify the type of boolean in case explicit declaration is not made using boolean keyword based on value stored.
// Implicit type inference
let isValidURL = false ;
console.log( 'typeof isValidURL : ' , typeof isValidURL)
// output : typeof isValidURL : , boolean
We cannot assign any other value like string or number to a boolean variable or we will get TypeScript error.
// defining a boolean variable
let hasValue : boolean ;
hasValue = true
// no error
hasValue = 1
// Error : Type 'number' is not assignable to type 'boolean'.
Operators supported in TypeScript for Boolean
Summary
- TypeScript uses boolean keywork to define Boolean data type.
- Boolean can hold either
trueorfalse.