Skip to content

[feature request(collections)] option to merge undefined in deepMerge #4752

Open
@scarf005

Description

@scarf005

Is your feature request related to a problem? Please describe.

when merging together deeply nested object (e.g react state), it's important to get 'nonempty' values when merging 'empty' values with 'nonempty' values.

for array, map and set it defaults to merging empty and non-empty values together:

deepMerge({ a: new Set([1]) }, { a: new Set() })
//=> { a: Set(1) { 1 } }

however, it doesn't work with nullish values. it'd be very useful to be able to output non-nullish value from merging nullish and non-nullish value together.

deepMerge({ a: 1 }, { a: undefined })
//=> { a: undefined }
// expected: { a: 1 }

Describe the solution you'd like

in DeepMergeOptions, add nullish: MergingStrategy that controls whether deepMerge will choose non-nullish value over nullish ones, such that

type State = {
  pos: {
    x: number
    y: number
  }
}
type UpdateState = Partial<{
  pos: Partial<{ 
    x: number
    y: number 
  }>
}>

const merge = (state: State, newState: UpdateState): State => deepMerge(state, newState, { nullish: "merge" })

always holds. (currently the return type of merge will be UpdateState)

Describe alternatives you've considered

make nullish: "merge” as default. this may cause breaking changes.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions