Within my api
function, I utilize a parser function that is generic and typically returns the same type as its input. However, in some cases, this may be different for simplification purposes.
When using the api
function, I am able to determine the type that will be passed to the parser input (usually a string
due to templating other parameters within the api
function).
My challenge lies in setting the return type of the api
function based on the output type of a parse
function without specifying an argument for its template.
// Relevant code snippet from library
type Parse = <T>(val: T) => any
let api = <P extends Parse>(
parse: P,
) =>
parse("xxx") as ???
// Usage example
let identity = <T>(val: T): T => val
let res = api(identity)
I have attempted several methods, but encountered obstacles due to the inability to access the implementation of the parse
function:
let api = <P extends Parse>(
parse: P,
) =>
parse("xxx") as ReturnType<P<string>> // error "Type P is not generic"
// Unable to specify type arguments of generic function type
let api = <P extends Parse>(
parse: P,
) =>
parse("xxx") as P extends (val: string) => infer O ? O : never // Result unknown
let api = <P extends Parse>(
parse: P,
) =>
parse("xxx") as ReturnType<typeof parse<string>> // Result is any, instantiation expression does not work effectively either
It's important to note that while I can modify the Parse
type if necessary, I do not have direct access to alter the implementation of the parse
function itself, which can vary within the constraints of the Parse
type.