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.
Code
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,2How the pieces connect
Under the hood: the function render.
What to watch for
- Constructed without dependencies — the registry and lockfile stay untouched.
- The guard
sizeleaves the path early viareturnwhen 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
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.