I am attempting to develop a double
function with the following structure:
type MaybeArray<T> = T | T[];
function double<T extends MaybeArray<number>>(data: T): T extends number[] ? number[] : number {
if (Array.isArray(data)) {
// TypeScript fails to recognize that `data` is an array of numbers in this section.
return data.map((n) => double(n));
}
// TypeScript fails to recognize that `data` is a number outside the previous condition.
return data * 2;
}
The goal is for the function to output the doubled value of the provided number, or an array with the doubled values if given a list. Please refer to any errors in the linked playground above.
However, TypeScript struggles to identify whether the parameter `data` within the if
block is an array of numbers and recognizes it as a plain number outside the block.
Is there a way to correct this issue without utilizing any overloads?
P.S.: I acknowledge that employing function overloads could resolve this dilemma, but I am interested in discovering alternative solutions.