Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The boolean type in TypeScript is a primitive data type representing a logical entity that can strictly hold one of two literal values: true or false. It directly corresponds to the underlying JavaScript boolean primitive and serves as the foundational type for logical operations and control flow evaluation.

Type Annotation and Inference

TypeScript can either explicitly enforce the boolean type via type annotations or implicitly infer it from the assigned value during initialization.
// Explicit type annotation
let isCompiled: boolean = false;

// Implicit type inference (TypeScript infers 'boolean')
let isExecuting = true; 

Boolean Literal Types

TypeScript’s type system allows narrowing the boolean type to its specific literal constituents. A variable typed as a boolean literal can only accept that exact value.
let strictlyTrue: true = true;

// Type Error: Type 'false' is not assignable to type 'true'.
strictlyTrue = false; 

Primitive boolean vs. Object Boolean

A critical distinction in TypeScript is the difference between the lowercase boolean primitive and the uppercase Boolean object wrapper. TypeScript strictly enforces the use of the primitive type for standard logical operations.
// Standard primitive (Recommended)
let primitiveFlag: boolean = true;

// Object wrapper (Anti-pattern)
let objectFlag: Boolean = new Boolean(false);

// Type Error: Type 'Boolean' is not assignable to type 'boolean'.
// 'boolean' is a primitive, but 'Boolean' is a wrapper object.
let mismatchedFlag: boolean = new Boolean(true);
Note: The Boolean object evaluates to truthy regardless of its internal state, which breaks standard logical evaluation. Always use boolean.

Strict Null Checks

Under TypeScript’s strict mode (specifically with the strictNullChecks compiler option enabled), a boolean type cannot be assigned null or undefined. It must be explicitly initialized with a boolean value.
let isValid: boolean;

// Type Error: Type 'null' is not assignable to type 'boolean'.
isValid = null; 

// Type Error: Type 'undefined' is not assignable to type 'boolean'.
isValid = undefined; 

// To allow nullability, a union type must be explicitly declared:
let isNullableValid: boolean | null | undefined = null;

Type Coercion to Boolean

When converting non-boolean types to a boolean primitive, TypeScript recognizes both the double-negation operator (!!) and the global Boolean() function (invoked without the new keyword) as valid type coercions returning a boolean type.
let rawData: string = "payload";

// Both methods correctly resolve to the 'boolean' type
let hasData: boolean = !!rawData;
let hasDataExplicit: boolean = Boolean(rawData);
Master TypeScript with Deep Grasping Methodology!Learn More