Unfortunately, there is no direct method to convert a union type into an intersection type. The limitations are highlighted in the definition of Object.assign
:
assign<T, U>(target: T, source: U): T & U;
assign<T, U, V>(target: T, source1: U, source2: V): T & U & V;
assign<T, U, V, W>(target: T, source1: U, source2: V, source3: W): T & U & V & W;
assign(target: object, ...sources: any[]): any;
The TypeScript declaration file lib.d.ts
offers typed versions for handling up to three sources, beyond which sources
resorts to an array of any
, losing type safety.
An alternate approach could involve:
// Public function signatures
function arrayToObject<T>(array:[T]):T
function arrayToObject<T, T2>(array:[T, T2]):T & T2
function arrayToObject<T, T2, T3>(array:[T, T2, T3]):T & T2 & T3
function arrayToObject<T, T2, T3, T4>(array:[T, T2, T3, T4]):T & T2 & T3 & T4
function arrayToObject<T>(array:T[]):T // accommodate more or dynamic values
// Implementation signature
function arrayToObject<T>(array:T[]):T {
return array.reduce((r,c) =>Object.assign(r,c))
}