TypeScript-safe truthiness filters: narrow out nullish values without dropping 0 or ''
Use an explicit nullish predicate instead of truthiness when arrays may contain legitimate falsy values. The article shows a runnable filterNullish helper, boundary tests, and the TypeScript narrowing rule that sits beside them.
The easiest way to remove "empty" values from a JavaScript array is also the easiest way to lose real data. `filter(Boolean)` and `filter(x => !!x)` remove every falsy value, not just `null` and `undefined`. That means `0`, `''`, `false`, and `NaN` disappear too, even when they are valid domain values. In TypeScript, that distinction matters twice: once at runtime, and once in the way the compiler narrows types after a filter call. This revision focuses on the working runtime helper from the attached implementation and its tests. The helper is intentionally small: it removes only nullish values and keeps the rest. The article then explains what that helper can prove, what it cannot prove, and how TypeScript's narrowing rules relate to the runtime behavior without pretending a Node test can verify the compiler's inference.
The bug is not just style: truthiness drops values you may want to keep
The core mistake is treating "falsy" and "nullish" as if they meant the same thing. They do not. A truthiness check answers a broad question: "does this value coerce to false?" In JavaScript, the answer is yes for `0`, `''`, `false`, `NaN`, `null`, and `undefined`. If your actual goal is only to remove missing values, a truthiness filter is too wide and can silently change program meaning. A zero score vanishes, an empty label disappears, and a legitimate `false` flag gets lost with them.
That is why the safest replacement is not a cleverer truthiness expression. It is a narrower predicate that matches your intent. In this article, that intent is specifically "remove null and undefined, preserve everything else." The attached implementation does exactly that with `value !== null && value !== undefined`, and the tests cover the values that truthiness would accidentally remove. That makes the runtime rule visible and easy to verify: the filter is about nullish values, not about generic falsiness.
TypeScript enters the picture because it can often narrow arrays when a filter callback is written as a real predicate. But narrowing does not rescue ambiguous logic. If the callback says "truthy," TypeScript cannot safely infer that `0` or `''` are meant to stay. If the callback says "non-nullish," the compiler has a precise contract to follow. The right code starts with the right semantic question, not with a convenient shorthand that happens to compile.
- Truthiness means more than null/undefined.
- A nullish-only helper keeps meaningful falsy values.
- Narrowing only helps when the predicate matches the real contract.
export function isNonNullish(value) {
return value !== null && value !== undefined;
}
export function filterNullish(values) {
if (!Array.isArray(values)) {
throw new TypeError('filterNullish expects an array');
}
return values.filter(isNonNullish);
}
export function removeNullish(values) {
return filterNullish(values);
}
SourcesTypeScript — Narrowing (opens a new tab)TypeScript 5.5 — Inferred Type Predicates (opens a new tab)
What the runnable helper does, and why it is deliberately small
The attached implementation is intentionally defensive but not fancy. `filterNullish(values)` first checks that the input is an array and throws a `TypeError` if it is not. That guard keeps the function honest about its input contract. After that, it uses `values.filter(isNonNullish)` to produce a new array with only `null` and `undefined` removed. The exported `removeNullish` function is just an alias that preserves the same behavior, which makes the public intent easier to read in call sites that prefer a verb phrase over a filter noun.
The important point is what the helper does not do. It does not try to interpret `0`, `''`, `false`, or `NaN` as missing. It does not normalize data. It does not guess whether falsy values should be excluded. Those are separate application decisions. By limiting the helper to nullish filtering, the implementation stays easy to test, easy to reason about, and safe to reuse in arrays where `0` and `''` are valid and meaningful values. The tests reflect that design by checking that those values survive the filter unchanged.
This is the right level of abstraction for the question this article answers. A broader helper that removes all falsy values would answer a different question, and a helper that mutates its input would solve a different problem entirely. Here the goal is to keep a value array intact except for missing entries, because that is the narrowest rule the reader asked for. Everything else should remain visible in the result array unless a different business rule says otherwise.
- The helper throws on non-arrays instead of guessing.
- It removes only `null` and `undefined`.
- It preserves `0`, `''`, `false`, and `NaN`.
What the tests prove, and what they do not
The revised Node test file exercises actual behavior instead of checking for source-code strings. That is the main fix from the failed draft. One test passes an array containing `null`, `0`, `''`, `undefined`, `'ok'`, `false`, and `NaN`, then asserts that the output keeps every legitimate falsy value while removing only the nullish ones. Another test uses an all-nullish array and expects an empty result. A third test verifies that an empty array stays empty and that non-arrays throw the documented `TypeError`. A fourth test checks the predicate directly to confirm that `0` and `''` are treated as present values.
Those assertions are useful because they describe the runtime contract in the form the function actually executes. They catch the exact class of regression the article is about: if someone replaced `value !== null && value !== undefined` with `Boolean(value)` or `!!value`, the output would change and the test would fail. That is the right kind of evidence for this implementation. The test suite is not trying to prove everything about TypeScript; it is proving the JavaScript behavior that the helper exports at runtime.
That distinction matters. A Node test cannot, by itself, verify the compiler's narrowing behavior. Type narrowing is a static analysis feature, not a runtime event. You still need TypeScript itself, or at least editor hover information and `tsc`, to confirm that a predicate is recognized as a type guard in your own project. The tests here establish the runtime contract only. The article explains the compiler side separately so the reader does not mistake a passing test for proof of inferred types.
- Tests verify runtime behavior, not static type inference.
- Boundary coverage includes all-nullish input and non-array input.
- The tests fail if someone swaps in `Boolean(value)` or `!!value`.
import test from 'node:test';
import assert from 'node:assert/strict';
import { filterNullish, isNonNullish, removeNullish } from './main.mjs';
test('filterNullish removes only null and undefined, preserving legitimate falsy values', () => {
const input = [null, 0, '', undefined, 'ok', false, NaN];
const output = filterNullish(input);
assert.deepEqual(output, [0, '', 'ok', false, NaN]);
assert.equal(output.includes(0), true);
assert.equal(output.includes(''), true);
assert.equal(output.includes(false), true);
assert.equal(Number.isNaN(output[4]), true);
});
test('removeNullish matches filterNullish on an all-nullish input', () => {
const input = [null, undefined, null, undefined];
assert.deepEqual(removeNullish(input), []);
});
test('filterNullish handles empty arrays and rejects non-arrays', () => {
assert.deepEqual(filterNullish([]), []);
assert.throws(() => filterNullish(null), {
name: 'TypeError',
message: 'filterNullish expects an array'
});
});
test('isNonNullish is a simple runtime predicate for nullish checks', () => {
assert.equal(isNonNullish(0), true);
assert.equal(isNonNullish(''), true);
assert.equal(isNonNullish(null), false);
assert.equal(isNonNullish(undefined), false);
});
SourcesTypeScript 5.5 — Inferred Type Predicates (opens a new tab)
Where TypeScript narrowing fits beside the runtime helper
TypeScript narrowing is the compiler's way of refining a declared type after it sees a check the runtime can actually perform. In this problem, the useful check is not "is this value truthy?" but "is this value not nullish?" That difference is subtle in code and large in effect. A truthiness check removes more values than most array-cleanup code intends, while a nullish check matches the usual idea of "present" data much more closely. When TypeScript understands that distinction, `Array.prototype.filter` can produce a narrower element type and downstream code becomes easier to write safely.
The release notes for TypeScript 5.5 make the boundary especially clear. The compiler can infer type predicates from simple boolean-returning filter callbacks when the logic is specific enough, such as `x => x !== undefined`. But the notes also call out the exact trap this article is about: `!!x` is not a safe replacement when `0` might be a real value, because the false branch would mean either `undefined` or a legitimate zero. In other words, the compiler is being cautious for a reason. It is refusing to pretend that an ambiguous check means something more precise than it does.
That is why the article keeps the static and runtime stories separate. The runtime helper shows how to preserve meaningful falsy values. The TypeScript narrowing story explains why the helper's predicate should be explicit when you want the compiler to follow along. If you write a predicate that really means "not null or undefined," TypeScript can often understand that. If you write a predicate that means "truthy," then the compiler cannot safely assume your business rule, because your business rule may depend on `0` or `''` staying in the array.
- Static narrowing follows the actual predicate, not the author's hope.
- `!!x` is too broad when `0` or `''` are valid values.
- Use the compiler to follow an explicit contract, not an ambiguous shortcut.
SourcesTypeScript — Narrowing (opens a new tab)TypeScript 5.5 — Inferred Type Predicates (opens a new tab)
When you should not use truthiness, and when you still might
The safest default is to avoid truthiness filters whenever the array can contain legitimate falsy values. That includes scores, counts, flags, short text fields, and any data model where `0`, `''`, or `false` means something specific. In those cases, the helper in this article is the right shape: remove nullish only, preserve everything else. The tests make that contract visible so future edits do not accidentally broaden it. If a later change decides that `false` or `NaN` should also be removed, that should be a deliberate rule change with a different helper name and a different test suite.
There are still cases where truthiness is acceptable. If an array is truly "present values only" and every falsy value is garbage, a truthiness filter can be a short and readable cleanup step. The important thing is that this should be an explicit decision. A function named `dropFalsy` or a one-off script with that intent is fine if the business rule actually says to discard every falsy value. What is unsafe is using the shorthand while mentally thinking it only removes null and undefined.
That is the judgment call this article is trying to sharpen. If the values are sparse data from lookups, explicit nullish removal is usually what you want. If the values are intentionally booleans or other data where false is a valid state, truthiness is the wrong filter. The cost of being explicit is one small predicate. The benefit is that your runtime behavior, your tests, and TypeScript's narrowing can all tell the same story instead of three different ones.
- Use truthiness only when every falsy value is truly unwanted.
- Prefer a named nullish helper for counts, labels, and scores.
- Rename the helper if the semantics ever broaden.
Practical recommendation: make the contract visible at the call site
The best single-line answer is: use an explicit nullish predicate or helper, not `Boolean`, when you need to preserve `0` or `''`. In this revision, that recommendation is embodied by `isNonNullish`, `filterNullish`, and `removeNullish`. Those names are deliberately boring because boring code is easier to maintain. A reader does not need to infer whether the function preserves empty strings, zero, or false; the helper's name and implementation say so directly. That clarity is especially valuable in shared utilities, where a tiny semantic mismatch can spread across many call sites.
If you are writing TypeScript, the next step is to let the compiler help where it can. Write predicates that mirror the runtime intent, and then check the narrowed type in your editor or with `tsc`. Keep in mind that the Node tests in this article verify the runtime behavior only. They prove that nullish values are removed and that legitimate falsy values survive. They do not prove compile-time inference, because that is a separate toolchain step. Treat those two checks as complementary, not interchangeable.
That separation is the main lesson of the revised draft. Runtime tests are for runtime behavior. TypeScript narrowing is for static reasoning about the same code. A clean nullish helper lets both layers agree. A truthiness filter may look shorter, but it conflates different ideas and leaves you guessing about what got dropped. The safer path is explicit, testable, and narrow enough to preserve the values your domain still cares about. The moment a `0` or empty string matters, you need that extra precision.
- Runtime tests prove what values survive the filter.
- TypeScript narrowing proves what the compiler can safely infer.
- A named nullish helper makes both meanings clear.
SourcesTypeScript 5.5 — Inferred Type Predicates (opens a new tab)


