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'];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With