Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the return type depending on the parameter value in TypeScript

Tags:

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.

like image 847
Livio Brunner Avatar asked Jun 18 '18 17:06

Livio Brunner


1 Answers

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'];
}
like image 192
Livio Brunner Avatar answered Nov 17 '22 10:11

Livio Brunner