简体   繁体   中英

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

  • 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

设法通过将签名更改为

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM