Boolean in TypeScript

Pubblicato il: 21 dicembre 2025
sul canale di: Learn Language Hub
5
0

1) What is a boolean?
“In TypeScript, a boolean holds one of two values: true or false. We use booleans for flags, conditions, feature toggles, and anything that represents yes/no logic.”

let isLoggedIn: boolean = false; // explicit annotation
isLoggedIn = true; // ✅ OK
// isLoggedIn = "yes"; // ❌ Error

Key point:
boolean is the primitive type. It’s not the same as the Boolean object wrapper (we’ll see why that matters in a minute).

2) Inference (you don’t always need to annotate)
“TypeScript often infers boolean automatically. If the initializer is true or false, TypeScript knows the type.”

let darkMode = false; // inferred as boolean
darkMode = !darkMode; // ✅ OK

Tip: Use inference for local variables; add explicit types for public APIs.

3) Boolean operators
“Booleans work with the standard logical operators: ! (not), && (and), || (or).”

const hasAccess = true;
const isOwner = false;

const canEdit = hasAccess && isOwner; // false
const canView = hasAccess || isOwner; // true
const isAnonymous = !hasAccess; // false

Note:
&& and || short‑circuit—if the left side decides the result, the right side isn’t evaluated.

4) Truthy and falsy (and why to avoid it for types)
“In JavaScript, some values are ‘truthy’ or ‘falsy.’ In TypeScript, the expression if (value) narrows based on that. But for types, prefer real booleans rather than relying on truthiness.”

const name = ""; // empty string is falsy
if (name) {
// not executed
}

Rule of thumb:
Return actual booleans from functions, not arbitrary truthy/falsy values—this keeps your types clean.

5) Booleans in functions (parameters & returns)
“Annotate function parameters and return values to communicate intent. Here are examples with guards and toggles.”

function isAdult(age: number): boolean {
return age == 18;
}

function toggle(value: boolean): boolean {
return !value;
}

function showBanner(isNewUser: boolean): void {
if (isNewUser) {
console.log("Welcome!");
}
}

6) Narrowing with conditionals
“TypeScript narrows union types when you check a boolean.”

type Result = { ok: true; data: string } | { ok: false; error: string };

function handle(result: Result) {
if (result.ok) {
// here: result is { ok: true; data: string }
console.log(result.data);
} else {
// here: result is { ok: false; error: string }
console.error(result.error);
}
}


Takeaway:
A boolean property like ok: true | false is often used as a discriminant for safe branching.

7) Boolean literal types: true and false
“TypeScript can represent the literal types true and false. This is great for precise APIs.”

const locked = true as const; // type is literally `true`
type Locked = typeof locked; // Locked === true

function mustBeTrue(x: true) {}
// mustBeTrue(locked); // ✅
// mustBeTrue(false); // ❌ Error


Use case:
Precise constraints and discriminated unions.

8) Avoid the Boolean object wrapper
“Boolean with a capital ‘B’ creates an object wrapper, which is almost never what you want. It behaves differently in truthiness checks.”

const a: boolean = false;
const b: Boolean = new Boolean(false); // Object wrapper

console.log(Boolean(a)); // false
console.log(Boolean(b)); // true — objects are truthy!

if (b) {
// This runs, even though the wrapped value is 'false'
}


Rule:
Use boolean (primitive), not Boolean (object). If you see new Boolean(...), replace it with plain booleans.

9) Double‑bang (!!) and coercion
“Sometimes we coerce a value to a real boolean using !!. It turns truthy/falsy into true/false.”

const input = "hello";
const hasText: boolean = !!input; // true


Caution:
Prefer clear conversions—!! is fine, but don’t overuse it where explicit checks improve readability.

10) Optional values → boolean checks
“Optional or nullable fields often need a boolean check before use.”

type User = { email?: string | null };

function hasEmail(user: User): boolean {
return !!user.email;
}

function sendEmail(user: User) {
if (!user.email) return; // handles '', undefined, null
// safe to use user.email here
}

11) Booleans vs unions (when true/false isn’t enough)
“A boolean is great for 2 states. If you have more than two, use union types—don’t pile on more booleans.”

// ❌ Hard to manage:
type Bad = { isLoading: boolean; isError: boolean; isSuccess: boolean };

// ✅ Better with a union:
type Status = "idle" | "loading" | "success" | "error";


Tip:
Use boolean for simple toggles; use unions for multi‑state flows.

12) Pattern: options objects instead of boolean parameters
“Boolean parameters can be vague. Prefer descriptive options objects.”

// ❌ Unclear: what does 'true' mean?
function getUsers(includeInactive: boolean) { /* ... */ }

// ✅ Clear & extensible
function getUsers(options: { includeInactive?: boolean } = {}) { /* ... */ }
getUsers({ includeInactive: true });


In questa pagina del sito puoi guardare il video online Boolean in TypeScript della durata di ore minuti seconda in buona qualità , che l'utente ha caricato Learn Language Hub 21 dicembre 2025, condividi il link con amici e conoscenti, su youtube questo video è già stato visto 5 volte e gli è piaciuto 0 spettatori. Buona visione!