Truthiness Narrows Unions Not Primitives

A truthiness check drops falsy members like empty string and 0 from literal unions, but a plain number still includes zero — equality checks are required there.

TypescriptForm Validation

Code

typescriptsnippet
24 lines
type Draft = { size: '' | 'sm' | 'lg' | undefined; count: number };

function render({ size, count }: Draft): string {
  // Truthiness drops '' and undefined: size is 'sm' | 'lg' here
  if (size) {
    return `size ${size} with count ${count}`;
  }
  // count stays number in both branches — zero is not a literal member,
  // so an explicit comparison is the only way to single it out
  return `no size; count ${count === 0 ? 'is zero' : count}`;
}

console.log(render({ size: 'sm', count: 2 }));
console.log(render({ size: '', count: 0 }));
console.log(render({ size: undefined, count: 5 }));

// On plain-typed arrays, truthiness filters only null and undefined members
const names: (string | undefined)[] = ['ada', undefined, 'bo'];
const defined = names.filter((name) => name !== undefined);
console.log('defined names:', defined.join(','));

const counts: number[] = [0, 1, 2];
console.log('kept by !== 0:', counts.filter((n) => n !== 0).join(','));
console.log('truthy only:', counts.filter(Boolean).join(','));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

size sm with count 2
no size; count is zero
no size; count 5
defined names: ada,bo
kept by !== 0: 1,2
truthy only: 1,2

How the pieces connect

Under the hood: the function render.

What to watch for

  • Constructed without dependencies — the registry and lockfile stay untouched.
  • The guard size leaves the path early via return when its condition holds.

Putting it to use

Entry signature: function render({ size, count }: Draft)

The printout labels itself — defined names:, kept by !== 0:, truthy only: — when the file runs.

Core lines

return `no size; count ${count === 0 ? 'is zero' : count}`;
const defined = names.filter((name) => name !== undefined);
return `size ${size} with count ${count}`;

Interactive Tools for This Topic

FAQ

Does this work in a bare project with no dependencies file?
Yes — a bare project runs it as-is, since nothing needs declaring. The file defines `render` at load time.