简体   繁体   中英

Change the return type depending on the parameter value in TypeScript

I have the following function:

function doThing(shouldReturnObject: boolean): string | object {
    return shouldReturnObject ? { hello: 'world' } : 'hello world';
}

I want the return value to be an object when shouldReturnObject equals true, but a string, when it is false.

The solution is by overloading the function. Overload the function for each parameter value and update the return type like this:

doThing(shouldReturnObject: true):  object
doThing(shouldReturnObject: false): string
doThing(shouldReturnObject: boolean): string | object {
  return shouldReturnObject ? { hello: 'world' } : 'hello world';
}

This can also be achieved, if the parameter is an object. For example:

interface DoThingsSettings {
  lazyLoading: boolean;
}

doThing(settings: { lazyLoading: false} &  DoThingsSettings): object[]
doThing(settings: { lazyLoading: true} &  DoThingsSettings): string[]
doThing(settings: DoThingsSettings):  object[] |  string[] {
  return settings.lazyLoading ? [{ name: 'Peter' }] : ['/user/1'];
}

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