Search code examples
typescriptfunctiongenericstypesinterface

How to return optional generic type from function conditionally?


There is very simplified example of function that I have. It accepts optional generic type, and optional second parameter, which if provided, will return 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 I use it, even with generic provided, I'll always have value as Promise<string | number>; enter image description here

Everything is logical here, but I would like this function to work next way: if applyDataCallback parameter OR generic provided, I want my value to be only that generic. In case as on screenshot, I've provided generic , and applyDataCallback, but still have possible string here.

Any ideas how to handle such case?


Solution

  • The solution, is to add default function for applyDataCallback, which by default will transform value type to provided generic.

    applyDataCallback: (value: string) => T = (value) => value as T.
    

    And then always call this callback.

    const body = applyDataCallback(config.body)