Consider a scenario where we have a function called toArray
which takes an argument and returns it as an array if it is already an array, or returns an array containing the argument value:
// Here is the implementation of the toArray function:
export const toArray = <T>(value: T | T[]): T extends undefined ? [] : Array<T> => {
if (typeof value === "undefined") return [] as any;
return (Array.isArray(value) ? value : [value]) as any;
};
This function works perfectly when the argument type is not a union:
number => number[]
number[] => number[]
However, for unions, the result may not be as expected:
// Expected output
'a'|'b' => ('a'|'b')[]
// Current output
'a'|'b' => 'a'[] | 'b'[]
The question arises - How can TypeScript be instructed to infer an array of unions rather than a union of arrays?