JavaScript Conditional Spread Pattern
By Sunrostern · · 1 min read
Conditional Spread Pattern
...(options.publish && { publish: true })
What it means conceptually
If
options.publishis truthy, addpublish: trueto the object. Otherwise, add nothing.
It’s almost always used inside an object literal:
const payload = {
title: 'Hello',
...(options.publish && { publish: true }),
};
How it actually works
options.publish && { publish: true }If
options.publishistrue(or truthy), the expression evaluates to:If
options.publishisfalse,undefined,null,0, etc., it evaluates to:
...(object spread)Spreading
{ publish: true }adds the property.Spreading
false(or any non-object) does nothing in object spread (it’s silently ignored).
Resulting behavior
options.publishResulting objecttrue: { publish: true } is addedfalse: nothing is added.undefined: nothing is added
Equivalent, more explicit version
const payload: any = { title: 'Hello' };
if (options.publish) {
payload.publish = true;
}Important TypeScript nuance
If you want TypeScript to narrow types cleanly, this is usually fine.
But if publish has a specific union or optional type, you may want:
...(options.publish ? { publish: true } : {})
That version is sometimes friendlier to strict typing and avoids the boolean | object intermediate type.
Common real-world use cases
API request payloads
Feature flags
Conditional config options
GraphQL variables
OpenAPI / SDK request objects