Function return type depending on whether optional argument is passed

时间:2019-03-17 22:32:13

标签: typescript

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

  • if it was passed then return type should be equal to factory return type
  • else it should be any

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

1 个答案:

答案 0 :(得分:1)

设法通过将签名更改为

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