millsp / ts-toolbelt

👷 TypeScript's largest type utility library

Home Page:https://millsp.github.io/ts-toolbelt/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Custom merge types

moteus opened this issue · comments

🍩 Feature Request

I am working on a typesafe merge library, and I want to support special merge modes for arrays (e.g. concat)
So in runtime code will looks like merge({a: [{b: 1}, {c: 2}]}, {a: merge.ArrayConcat([{d: 3}])})
And result will be {a: [{b: 1}, {c: 2}, {d: 3}]}
One way to achieve such type is to use the L.Assign type but with L.Merge with custom basic merger like

// Here user logic
type MergeConcat <O1, O2 extends MergeArrayConcat<unknown>> =  
  O2 extends MergeArrayConcat<infer E> ? 
  O1 extends L.List ? L.Append<O1, E> : E
  : never

// Overwrite default behavior of L.Merger for the specific type.
type CustomMerge<O1, O2> = O2 extends MergeArrayConcat<unknown> ? MergeConcat<O1, O2> : DefaultMerge<O1, O2>

Here DefaultMerge is what the library uses right now to merge objects.
I am quite new to TypeScript and maybe you know a better solution for this problem?