let's say we have a function toArray
that takes an argument and returns it as is if it is an array and if not returns an array with the argument value:
// function that takes a value and returns the value if it is of type array and if not returns the value in an array
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 fine as long as the type of the arguments is not union:
number => number[]
number[] => number[]
for unions I got not the expected result:
// wanted
'a'|'b' => ('a'|'b')[]
// currently
'a'|'b' => 'a'[] | 'b'[]
How do I tell typescript to infer array of union instead of union of arrays?