Same like JavaScript, TypeScript also supports Boolean values. In TypeScript, the boolean data type is useful to define variables to accept only Boolean values (true
/false
).
Following is the syntax of defining the variables with boolean type in typescript.
[Keyword] [Variable Name]: [boolean] = [Value];
[Keyword] [Variable Name]: [boolean];If you observe the above syntax, we added a boolean
datatype after the variable name to tell the compiler that the boolean type of data the variable can hold.
var
, let
or const
to define the scope and usage of variables.Now, we will learn how to use boolean data types in TypeScript with examples.
Following is the example of defining the variables with boolean data type in typescript.
var isVerified: boolean = true;
var isDone: Boolean = false;
console.log(isVerified); // true
console.log(isDone); // false
If you observe the above boolean type example, we defined the variables with lower case boolean
type and upper case Boolean
type. Here, the lower case boolean
is a primitive type and the upper case Boolean
is an object type. In TypeScript, it’s always recommended to use primitive lower case boolean
type.
This is how we can use boolean type in typescript to define the variables to accept only boolean values based on our requirements.