I am currently working on developing a versatile sort
function that can function with or without promises seamlessly.
The intended structure of the function should look something like this:
function sort<T>(list: T[], fn: (item: T) => string | number): T[];
function sort<T>(list: Promise<T[]>, fn: (item: T) => string | number): Promise<T[]>;
The objective is to be able to use the function regardless of whether the input list
is a promise or not, while ensuring that the return type matches the input type.
I have implemented similar constructions for other data types, such as a map function that works for both arrays and objects. However, dealing with promises adds an extra layer of complexity, as marking the method as async
would require it to always return a promise.
Is there a way to achieve this? Can this be done?