In this code snippet, we have a simple example of a function that accepts an optional generic type and an optional second parameter. If the second parameter is provided, it will return the generic type.
const helper = async <T = void>(
config: { body: string},
applyDataCallback?: (value: string) => T,
): Promise<T | string> => {
const body = typeof (applyDataCallback) === 'function'
? applyDataCallback(config.body)
: config.body;
return body;
}
When using this function, even with a generic type provided, the value will always be a Promise<string | number>.
While this setup makes sense, I want the function to behave differently. If either the applyDataCallback parameter or the generic type is provided, I only want the value to be that generic type. In the current case shown in the screenshot, where both the generic type and applyDataCallback are provided, I still end up with a possible string as a result.
Any suggestions on how to address this scenario?
https://i.sstatic.net/dLG1k.png