How to Convert Number to Boolean in TypeScript

The quickest way to convert number to boolean in TypeScript is Boolean(n) or !!n. Both return false for 0, -0 and NaN, and true for every other number, including negatives and Infinity:

const isActive: boolean = Boolean(flag);   // same result as !!flag

I ran each snippet below with TypeScript 7.0.2 and Node.js v22.22.2 in strict mode, so the console output you see is real.

We’ll cover the three common conversions, nullable numbers, strict 0/1 flags from APIs and databases, the string “0” trap, compiler errors and how to go back from boolean to number.

Boolean(n) vs !!n vs n !== 0 for converting a number

Here’s every edge case side by side. You’ll want to watch the NaN row closely:

const samples: [string, number][] = [
  ["1", 1], ["0", 0], ["-5", -5], ["0.5", 0.5],
  ["-0", -0], ["NaN", NaN], ["Infinity", Infinity],
];

console.log("value     Boolean(n)  !!n    n !== 0");
for (const [label, n] of samples) {
  console.log(
    label.padEnd(10) +
      String(Boolean(n)).padEnd(12) +
      String(!!n).padEnd(7) +
      String(n !== 0)
  );
}

Output:

value     Boolean(n)  !!n    n !== 0
1         true        true   true
0         false       false  false
-5        true        true   true
0.5       true        true   true
-0        false       false  false
NaN       false       false  true
Infinity  true        true   true
Command Prompt output comparing Boolean(n), !!n and n !== 0 in TypeScript for 1, 0, -5, 0.5, -0, NaN and Infinity
Boolean() and !! always agree; n !== 0 says NaN is true.

Boolean(n) and !!n are identical, so choose by readability. I use Boolean() in shared code because a teammate can’t misread it.

n !== 0 is only safe when you’ve already ruled out NaN, for example after parsing user input. If the number came from a string, see converting a string to a double in TypeScript first.

Convert an optional number to a boolean

A count that may be null or undefined converts the same way, and TypeScript still types the result as boolean:

function hasOrders(count: number | null | undefined): boolean {
  return Boolean(count);
}

console.log("3 orders:   ", hasOrders(3));
console.log("0 orders:   ", hasOrders(0));
console.log("null:       ", hasOrders(null));
console.log("undefined:  ", hasOrders(undefined));

Output:

3 orders:    true
0 orders:    false
null:        false
undefined:   false

If you need to tell “zero” apart from “missing”, don’t collapse it to a boolean. Check count === undefined first. More on narrowing is in checking the type of a variable in TypeScript.

How do I convert 1/0 flags from an API or database?

MySQL TINYINT(1) columns and many REST APIs send 1 and 0 instead of booleans. Truthiness would quietly turn a bad value like 2 into true, so I map strictly and fail loudly:

interface CustomerRow {
  id: number;
  name: string;
  city: string;
  is_active: number; // TINYINT(1) column: should be 0 or 1
}

function isFlag(value: number): value is 0 | 1 {
  return value === 0 || value === 1;
}

function toBool(value: number, field: string): boolean {
  if (!isFlag(value)) {
    throw new RangeError(`${field} must be 0 or 1, got ${value}`);
  }
  return value === 1;
}

const rows: CustomerRow[] = [
  { id: 101, name: "Avery Johnson", city: "Austin, TX", is_active: 1 },
  { id: 102, name: "Mason Lee", city: "Columbus, OH", is_active: 0 },
  { id: 103, name: "Harper Davis", city: "Portland, OR", is_active: 2 },
];

for (const row of rows) {
  try {
    const active = toBool(row.is_active, "is_active");
    console.log(`${row.id} ${row.name.padEnd(14)} active=${active}`);
  } catch (err) {
    const e = err as Error;
    console.log(`${row.id} ${row.name.padEnd(14)} ${e.name}: ${e.message}`);
  }
}
console.log("Boolean(2) would have said:", Boolean(2));

Output:

101 Avery Johnson  active=true
102 Mason Lee      active=false
103 Harper Davis   RangeError: is_active must be 0 or 1, got 2
Boolean(2) would have said: true
Command Prompt output of a TypeScript strict 0/1 flag conversion that throws RangeError for the value 2
Rows with 1 and 0 convert cleanly; the row with 2 throws a RangeError instead of becoming true.

isFlag() is a type predicate, so after the check TypeScript knows value is 0 | 1. I explain that pattern in the is keyword in TypeScript.

Throwing beats guessing here. A bad customer record that silently shows as active is much harder to track down later.

Why is Boolean(“0”) true in TypeScript?

Any non-empty string is truthy, so Boolean("0") and Boolean("false") both return true. Query strings, form fields and CSV cells are always strings, so this bites often:

const params = new URLSearchParams("active=0&newsletter=1&beta=false");
const active: string = params.get("active") ?? "";

console.log('Boolean("0"):       ', Boolean(active));
console.log('Boolean("false"):   ', Boolean(params.get("beta")));
console.log('Boolean(""):        ', Boolean(""));
console.log('Boolean(Number("0")):', Boolean(Number(active)));
console.log('Number(""):         ', Number(""));

function paramToBool(value: string | null): boolean | undefined {
  if (value === "1" || value === "true") return true;
  if (value === "0" || value === "false") return false;
  return undefined; // missing or unexpected
}

console.log("active:    ", paramToBool(params.get("active")));
console.log("newsletter:", paramToBool(params.get("newsletter")));
console.log("beta:      ", paramToBool(params.get("beta")));
console.log("promo:     ", paramToBool(params.get("promo")));

Output:

Boolean("0"):        true
Boolean("false"):    true
Boolean(""):         false
Boolean(Number("0")): false
Number(""):          0
active:     false
newsletter: true
beta:       false
promo:      undefined
Command Prompt output showing TypeScript Boolean of the string 0 and the string false returning true, plus a strict paramToBool helper
The string “0” is true, Number("0") fixes it, and paramToBool returns undefined for a missing value.

Converting with Number() first works, but Number("") is also 0, so a blank field becomes false. Comparing against the exact strings you expect is safer.

For empty input checks, see checking if a string is empty in TypeScript.

TypeScript errors when mixing numbers and booleans

Strict TypeScript won’t convert a number for you. Each of these lines fails to compile:

const isActive: boolean = 1;

const count: number = 3;
const hasOrders: boolean = count;

if (count === true) {
  console.log("never runs");
}

const both = true + true;

Output:

num2bool_errors.ts(1,7): error TS2322: Type 'number' is not assignable to type 'boolean'.
num2bool_errors.ts(4,7): error TS2322: Type 'number' is not assignable to type 'boolean'.
num2bool_errors.ts(6,5): error TS2367: This comparison appears to be unintentional because the types 'number' and 'boolean' have no overlap.
num2bool_errors.ts(10,14): error TS2365: Operator '+' cannot be applied to types 'boolean' and 'boolean'.
Command Prompt output of tsc errors TS2322 number is not assignable to type boolean, TS2367 and TS2365
TS2322 for both assignments, TS2367 for comparing a number to true, and TS2365 for adding two booleans.

The fix for TS2322 is always an explicit conversion: Boolean(count) or count === 1. For TS2367, compare the number to a number, not to true.

Convert a boolean back to a number

Going the other way is simple. Number(true) is 1 and Number(false) is 0, and a ternary makes the intent obvious:

const optedIn: boolean[] = [true, false, true, true, false];

console.log("Number(true): ", Number(true));
console.log("Number(false):", Number(false));
console.log("ternary:      ", optedIn.map((b) => (b ? 1 : 0)).join(", "));

const yes = optedIn.filter(Boolean).length;
const viaSum = optedIn.reduce((total, b) => total + Number(b), 0);
console.log("opted in:", yes, "of", optedIn.length, "| reduce:", viaSum);

Output:

Number(true):  1
Number(false): 0
ternary:       1, 0, 1, 1, 0
opted in: 3 of 5 | reduce: 3

filter(Boolean).length is my favorite way to count true values. Don’t use it on numbers, though, since it drops every 0; see filtering arrays in TypeScript.

If your flags live in an enum, converting a TypeScript enum to a number shows how to get the 0 or 1 back out. For text output, use converting a boolean to a string.

Number to boolean methods in TypeScript compared

MethodNaN becomesBest for
Boolean(n)falseReadable truthiness checks
!!nfalseShort inline conversions
n !== 0trueNumbers already validated
n === 1 with a 0/1 guardErrorAPI and database flags
s === "1" on stringsn/aQuery strings and form fields

A few more TypeScript conversion guides you might find useful:

Frequently asked questions

How do I convert a number to a boolean in TypeScript?

Use Boolean(n) or !!n. Zero, negative zero and NaN become false; every other number becomes true.

Is there a difference between Boolean(n) and !!n?

No. Both apply the same truthiness rules and return a primitive boolean. Pick the one your team reads more easily.

Why is NaN true with n !== 0?

NaN isn’t equal to anything, including 0, so NaN !== 0 is true. Boolean(NaN) is false.

How do I convert only 0 and 1 to a boolean?

Check the value first and throw for anything else, then return value === 1. That stops a 2 from becoming true.