To add a boolean type annotation to a variable or a constant, you can declare the variable or constant followed by a :
(colon) symbol and then the type boolean
in TypeScript.
For example, let's say we have a variable called isPerson
and want to only have the boolean
type as the values. To do that we can annotate the type boolean
to the isPerson
variable like this,
// add boolean type to a variable
let isPerson: boolean;
After initialization, let's assign a boolean value of true
to the variable isPerson
. It can be done like this,
// add boolean type to a variable
let isPerson: boolean;
// assign a boolean value to the isPerson variable
isPerson = true; // ✅ allowed
As you can see from the above code TypeScript allowed us to assign the boolean value of true
to the variable isPerson
since the allowed type for the isPerson
variable is boolean
.
Now let's try to assign another value of string
type Hello World!
to the isPerson
variable to see what happens,
// add boolean type to a variable
let isPerson: boolean;
// assign a boolean value to the isPerson variable
isPerson = true; // ✅ allowed
// assign a value of type other than a boolean
isPerson = "Hello World!"; // ❌ not allowed. Type 'string' is not assignable to type 'boolean'.
As you can see that the TypeScript will throw an error saying that the Type 'string' is not assignable to type 'boolean'.
which is also what we want to happen.
Bonus
Most of the time TypeScript will try to infer the type of the variable from the value it is assigned.
For example, let's declare a variable called myFavBool
and assign the boolean
value of 'true' without actually declaring the type boolean
as we did above. It can be done like this,
// Typescript infers the type from
// the value it is assigned
let myFavBool = true;
Now if you hover over the variable myFavBool
we can see that TypeScript has automatically got that type of the variable myFavBool
is of type boolean
.
Since the TypeScript has already got the type is of boolean
value and whenever we try to reassign a value other than the type boolean
, The compiler will throw errors like from the above.
See the execution of the above codes live in codesandbox.
That's all 😃!