Wilhelm Olejnik
Wilhelm Olejnik

Reputation: 2507

Function return type depending on whether optional argument is passed

I am trying to create a function with return type depending on whether optional parameter (factory) was passed or not

I tried to do it like this:

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();             // OK, treated as date
getObject(1, () => new String()).toLocaleLowerCase(); // OK, treated as string
getObject(1).anything; // ERROR, typescript treat it as {} instead of any 

but It doesn't work as expected when I don't pass factory parameter. How can I fix it? https://stackblitz.com/edit/typescript-xci2gs

Upvotes: 2

Views: 119

Answers (1)

Wilhelm Olejnik
Wilhelm Olejnik

Reputation: 2507

Managed to fix it by changing the signature to

function getObject<T extends Factory<any>>(id: number, factory?: T): T extends undefined ? any : ReturnType<T> {

Upvotes: 1

Related Questions