-
Notifications
You must be signed in to change notification settings - Fork 1.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Type-narrowing doesn't work #3055
Comments
I don't think |
@Ram4GB My bad. Fixed the example! |
I assume you request the user who is not found in your database or has been deleted by other actions. In this case, the API must throw the error with the status |
Not sure to understand. I'm just saying if "isLoading" is false, then "data" should become of type "number". It is a basic functionality of TanStack query: https://tanstack.com/query/latest/docs/framework/react/typescript#type-narrowing |
But if fetching fails/errors, there won't be data, and it won't be loading either. |
@icyJoseph Updated my example. Makes sense? Basically I'm asking for the same thing than TanStack Query. |
Yes @lcswillems, your example is not clear to me. In your case, I believe we should get the type |
Yes we should get the type |
@lcswillems
|
Thank you for sharing!
The 4th and best option would be to improve the typing of the library. |
@lcswillems Your example
TanStack query
TanStack query creates a new field |
@samuel871211 In TanStack query, this also narrows down:
And I'm wondering what prevents SWR to narrow down here:
? |
Your code example doesn't work for me. const { data, isLoading, isError } = useQuery({ ... });
if (!isLoading && !isError) {
data
// ^? const data: number
} ![]()
Original Codebase before PR export interface SWRResponse<Data = any, Error = any, Config = any> {
/**
* The returned data of the fetcher function.
*/
data: BlockingData<Data, Config> extends true ? Data : Data | undefined
......
}
export type BlockingData<
Data = any,
Options = SWROptions<Data>
> = Options extends undefined
? false
: Options extends { suspense: true }
? true
: Options extends { fallbackData: Data | Promise<Data> }
? true
: false The type of data is |
@samuel871211 Sorry it is "isPending" that needs to be used: https://stackblitz.com/edit/github-j5aexizp?file=src%2Findex.tsx |
Bug report
Description / Observed Behavior
Expected Behavior
It should be of type
number
.The text was updated successfully, but these errors were encountered: