I am attempting to design a function that will have a return type based on whether an optional parameter (factory) is provided or not
- If the factory parameter is passed, then the return type should match the return type of the factory
- Otherwise, it should default to 'any'
This is how I tried to implement it:
type Factory<T> = (data: any) => T;
function getObject<T>(id: number, factory?: Factory<T>): Factory<T> extends undefined ? any : ReturnType<Factory<T>> {
let obj; // some entity from db in real app
return factory ? factory(obj) : obj;
}
getObject(1, () => new Date()).getDate(); // Works fine, treated as a date
getObject(1, () => new String()).toLocaleLowerCase(); // Correctly recognized as a string
getObject(1).anything; // This results in an error, TypeScript interprets it as {} instead of any
However, when I do not provide the factory
parameter, it does not behave as expected. What changes can I make to fix this?
https://stackblitz.com/edit/typescript-xci2gs