Skip to content
public-library›TypeScripttechs/typescript

Use Boolean() for explicit boolean coercion

Sign in to star Use Boolean() for explicit boolean coercion, 0 stars

Sign in to star rules

Star this rule if you find it useful.

Add to cart

What would you like to add?

At checkout, you'll pick which project these go into, and you can fork a rule instead of staying in sync.

When to apply

Before writing, changing, or reviewing TypeScript code that converts a value to a boolean, such as !!value, or tests a value's truthiness.

When code intentionally converts a value to a boolean from its truthiness, write Boolean(value) instead of !!value. When the condition has a specific meaning, such as "present" or "non-empty", write that comparison instead of coercing.

Implementation

  • Replace !!value with Boolean(value).
  • Compare against the specific absent value, such as value !== undefined, when you need TypeScript to narrow the variable afterward; Boolean(value) in a separate variable does not narrow it.
  • Keep domain comparisons, such as count > 0, name.trim() !== '', or status === 'ready'; they say which condition matters.

This is a readability convention.

Rationale

Boolean(value) names the intent and is easy to search for, while !! is a symbol pair that readers can overlook. Truthiness also treats 0, '', and NaN as false, which is often not what a condition means; an explicit comparison makes the excluded cases visible.

Examples

Incorrect (counterexample):

const hasAccount = !!accountContext;

Correct:

const hasAccount = Boolean(accountContext);
const canView = accountContext !== undefined && sharedFile.allowedAccountIds.includes(accountContext.id);

Validation

Search for !! and replace intentional coercions with Boolean() or a specific comparison.

A specific comparison, such as count > 0, is not a violation.