Currently, I am attempting to write a function that accepts an optional transformResult
. My challenge lies in correctly typing the useQuery
function to achieve the following:
- If
transformResult
is not provided, it should return a type ofQResult
. - If the callback is provided, it should return
TResult
(or the return type of thetransformResult
callback, if possible).
How can this be accomplished? While I am open to using function overrides for an easy solution, I prefer conditional types.
Thank you in advance for your help!
type QueryOptions<QResult, TResult> = {
transformResult?: (queryResult: QResult) => TResult;
// Other options that are not so important
enableDebug?: boolean;
};
function useQuery<QResult, TResult = QResult>(
query: string,
options?: QueryOptions<QResult, TResult>,
) {
const queryResult = doSomeServerStuff<QResult>(query);
if (options?.transformResult != null) {
return options.transformResult(queryResult);
} else {
return queryResult;
}
}
function doSomeServerStuff<Q>(query: string): Q {
/* Not so important just to make it compile */
return {} as Q;
}
//typeOf 'number' <- Good
const result = useQuery<number>('q');
// Expecting 'boolean' type, but 'number | boolean' is actual
const transformedResult = useQuery<number, boolean>('q', {
transformResult: (qResult) => qResult != null,
});
Access the TypeScript playground here.