T
TanStack•7mo ago
manual-pink

Query Return Type when using `select`

Hi all. I guess this is more of a TS question than query related but I've been wondering how to best practice the return type when using select on data retrieval? My query calls the API to get a data set which has it's own type - but I've also built in a parsing flag for the data set which returns another type if true. The type gets inferred as Type1 | Type2 . Is there a good way to infer type 2 only if the flag is true and use type1 if the flag is false? Or is it best to just split the query function into two separate entities ( with same queryKey , but one uses the parsing and the other doesn't )? Cheers on any info or pointers what's cleaner 😄
1 Reply
unwilling-turquoise
unwilling-turquoise•7mo ago
I think I understand what you mean and I've messed around with something like that, you should be able to define a queryOptions helper with a conditional return type, i.e.
function getMyQueryOptions<T extends boolean>(myFlag: T): T extends true ? Type1 : Type2 {
return queryOptions({ … });
}
function getMyQueryOptions<T extends boolean>(myFlag: T): T extends true ? Type1 : Type2 {
return queryOptions({ … });
}
But I think you might have to explicitly cast your return value So something like
function getMyQueryOptions<T extends boolean>(myFlag: T): T extends true ? Type1 : Type2 {
return queryOptions({
queryKey: ['myKey', myFlag],
queryFn: fetchMyData(myFlag),
select: data => {
if (myFlag) {
return parseType1(data);
}

return parseType2(data);
}
});
}
function getMyQueryOptions<T extends boolean>(myFlag: T): T extends true ? Type1 : Type2 {
return queryOptions({
queryKey: ['myKey', myFlag],
queryFn: fetchMyData(myFlag),
select: data => {
if (myFlag) {
return parseType1(data);
}

return parseType2(data);
}
});
}
With possibly a cast in there somewhere You can probably also just overload that query helper function: https://www.typescriptlang.org/docs/handbook/2/functions.html#function-overloads

Did you find this page helpful?