index/functions/conditionalSpreadBuilder.md
conditionalSpreadBuilder<
T>(baseObj,conditionalFields):T&Record<string,unknown>
Build object with conditionally spread fields
Takes a base object and conditionally spreads fields only if they are defined.
Uses the pattern: { ...baseObj, ...(field ? { field } : {}) } to clean up code
and make intent explicit.
Consolidates 2 occurrences across PoolStateManager and agent-config utilities.
base obj conditional fields
Type Parameters
| Type Parameter | Description |
|---|---|
T | The base object type |
Parameters
| Parameter | Type | Description |
|---|---|---|
baseObj | T | The base object to start with |
conditionalFields | Record<string, unknown> | Object where each value determines if that field is included |
base obj conditional fields
Returns
T & Record<string, unknown>
New object with base fields plus defined conditional fields
Examples
// Simple conditional field
const config = conditionalSpreadBuilder(
{ id: '123', name: 'test' },
{ description: descriptionValue }
);
// If descriptionValue is defined: { id: '123', name: 'test', description: '...' }
// If descriptionValue is undefined: { id: '123', name: 'test' }
// Multiple conditional fields
const event = conditionalSpreadBuilder(
{ id: 'evt-1', timestamp: Date.now() },
{
source: sourceValue, // included if sourceValue is defined
metadata: metadataObj, // included if metadataObj is defined
tags: tagsArray // included if tagsArray is defined
}
);
// Returns object with only non-undefined fields from conditionalFields
// Replaces pattern:
// Old: { ...baseConfig, ...(config?.option ? { option: config.option } : {}) }
// New: conditionalSpreadBuilder(baseConfig, { option: config?.option })
// Works with falsy values (only undefined is excluded)
const obj = conditionalSpreadBuilder(
{ value: 10 },
{
count: 0, // included (0 is defined)
empty: '', // included ('' is defined)
nullValue: null, // included (null is defined)
undefinedValue: undefined // excluded (undefined)
}
);
// Returns: { value: 10, count: 0, empty: '', nullValue: null }
Remarks
- Only fields with
undefinedvalues are excluded - All other falsy values (0, '', null, false) ARE included
- This matches the common spread pattern behavior exactly
- Order preserved: base fields first, then conditional fields
- Does not mutate input objects
See
buildWithOptionalFields for a similar pattern that filters on non-empty strings