Skip to content

Conversation

leesb971204
Copy link
Contributor

@leesb971204 leesb971204 commented Aug 18, 2025

This PR updates the TypeScript docs for Registering a global error:

  • Changed the example to recommend defaultError = unknown instead of AxiosError.
  • Added rationale:
    • By default, the error type in TanStack Query is inferred as Error.
    • However, if developers want to make the error type safer and more explicit, they can override the global default to unknown.
    • Errors in TanStack Query are not limited to your queryFn; they may also come from select, memoized callbacks, or other user-land code.
    • Using AxiosError globally can mislead developers into thinking all errors originate from Axios, which is incorrect.

discussions in here

Summary by CodeRabbit

  • Documentation
    • Updated TypeScript guidance to prefer using unknown for documented error types (defaultError) so call sites must explicitly narrow errors.
    • Revised examples across React, Solid, Angular and Vue docs to show error typed as unknown | null with comments demonstrating required narrowing.
    • Improved snippet formatting and added anchor markers for clarity.
    • Clarified these are documentation-only, non-runtime changes.

Copy link

coderabbitai bot commented Aug 18, 2025

Walkthrough

Docs-only updates: examples in React, Solid, Angular, and Vue TypeScript guides change Register.defaultError from AxiosError to unknown, update shown query.error type to unknown | null, and add snippet anchor/formatting markers or comments.

Changes

Cohort / File(s) Summary
Docs — React TypeScript
docs/framework/react/typescript.md
Replaced AxiosError with unknown for Register.defaultError in example module augmentation; updated example error type to `unknown
Docs — Solid TypeScript
docs/framework/solid/typescript.md
Replaced AxiosError with unknown for Register.defaultError in example module augmentation; updated example error type to `unknown
Docs — Angular TypeScript
docs/framework/angular/typescript.md
Replaced AxiosError with unknown for Register.defaultError in example module augmentation; updated example error type to `unknown
Docs — Vue TypeScript
docs/framework/vue/typescript.md
Added module augmentation showing Register.defaultError: unknown; example shows query.error inferred as `unknown

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

I hop through docs with careful cheer,
I swap a type so callers steer clear.
Unknown now waits, a quiet guest,
Narrow with care — put checks to the test.
A rabbit nods, the docs look best. 🐇✨

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@github-actions github-actions bot added the documentation Improvements or additions to documentation label Aug 18, 2025
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
docs/framework/react/typescript.md (2)

158-168: Import isAxiosError or qualify it to prevent an undefined identifier in the snippet

As written, isAxiosError will be undefined in this snippet. Either import it or qualify via axios.isAxiosError.

Apply one of the following diffs:

Option A — import the named helper:

 ```tsx
+import { isAxiosError } from 'axios'
 const { error } = useQuery(options)

 if (isAxiosError(error)) {
   // handle Axios-specific details
 } else if (error instanceof Error) {
   // handle generic errors
 } else {
   // handle non-Error throwables if needed
 }

Option B — use the default export qualifier (and import it):
```diff
 ```tsx
+import axios from 'axios'
 const { error } = useQuery(options)

-if (isAxiosError(error)) {
+if (axios.isAxiosError(error)) {
   // handle Axios-specific details
 } else if (error instanceof Error) {
   // handle generic errors
 } else {
   // handle non-Error throwables if needed
 }

---

`170-187`: **Define `normalizeToDomainError` and strengthen `DomainError` subclassing for clarity and correctness**

Readers may look for `normalizeToDomainError`. Adding a minimal example helps. Also, setting `name` and prototype improves Error subclassing robustness.



```diff
 ```tsx
+import { isAxiosError } from 'axios'
 class DomainError extends Error {
   constructor(public kind: 'Network' | 'Auth' | 'Unknown', message?: string) {
     super(message)
+    this.name = 'DomainError'
+    // Ensures instanceof works reliably across transpilation targets
+    Object.setPrototypeOf(this, new.target.prototype)
   }
 }
 
+function normalizeToDomainError(e: unknown): DomainError {
+  if (isAxiosError(e)) {
+    // map Axios/network concerns
+    return new DomainError('Network', e.message)
+  }
+  if (e instanceof Error) {
+    // map other Errors
+    return new DomainError('Unknown', e.message)
+  }
+  // handle non-Error throwables
+  return new DomainError('Unknown', String(e))
+}
+
 const queryFn = async () => {
   try {
     const res = await api.get('/user')
     return res.data
   } catch (e) {
     throw normalizeToDomainError(e) // convert AxiosError or others → DomainError
   }
 }

</blockquote></details>

</blockquote></details>

<details>
<summary>📜 Review details</summary>

**Configuration used: CodeRabbit UI**
**Review profile: CHILL**
**Plan: Pro**

**💡 Knowledge Base configuration:**

- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

<details>
<summary>📥 Commits</summary>

Reviewing files that changed from the base of the PR and between b6516bd25edcc67dfaced09412f52c9660386a9b and 8b85d83aa5ea1191bc376995b2baa915c4103545.

</details>

<details>
<summary>📒 Files selected for processing (1)</summary>

* `docs/framework/react/typescript.md` (1 hunks)

</details>

<details>
<summary>🔇 Additional comments (2)</summary><blockquote>

<details>
<summary>docs/framework/react/typescript.md (2)</summary>

`133-150`: **Solid rationale and correct module augmentation for `defaultError: unknown`**

The shift to `unknown` avoids misleading global assumptions and keeps inference intact for the rest of the generics. The module augmentation pattern is correct and results in `error: unknown | null` at call sites as intended.

---

`189-189`: **Concise wrap-up reads well**

The closing sentence clearly reinforces the motivation without overpromising. LGTM.

</details>

</blockquote></details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->

@@ -130,24 +130,63 @@ if (axios.isAxiosError(error)) {

### Registering a global Error

TanStack Query v5 allows for a way to set a global Error type for everything, without having to specify generics on call-sides, by amending the `Register` interface. This will make sure inference still works, but the error field will be of the specified type:
TanStack Query v5 allows for a way to set a global Error type for everything, without having to specify generics on call-sides, by amending the `Register` interface. This will make sure inference still works, but the error field will be of the specified type. We recommend `unknown` to ensure safe, explicit narrowing at call sites, by amending the `Register` interface:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
TanStack Query v5 allows for a way to set a global Error type for everything, without having to specify generics on call-sides, by amending the `Register` interface. This will make sure inference still works, but the error field will be of the specified type. We recommend `unknown` to ensure safe, explicit narrowing at call sites, by amending the `Register` interface:
TanStack Query v5 allows for a way to set a global Error type for everything, without having to specify generics on call-sides, by amending the `Register` interface. This will make sure inference still works, but the error field will be of the specified type. If you want to enforce that call-sides must do explicit type-narrowing, set `defaultError` to `unknown`:


[//]: # 'RegisterErrorType'

```tsx
import '@tanstack/react-query'

// ✅ Recommended
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If this were “recommended”, we’d have kept it as unknown per default instead of Error. Error will work for 99.99% of cases, so going back to unknown is something you can do if you want the safest possible variant because you explicitly throw things that aren’t errors (which also isn’t recommended!), but let’s please not document that this is “recommended”.

```

[//]: # 'RegisterErrorType'

#### Why `unknown` instead of `AxiosError`?
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please remove this whole paragraph. The reference to AxiosError makes no sense anymore since it was removed from the previous paragraph, and it’s just confusing, and the pattern with try/catch in the queryFn is not something I would recommend. Instead, the API layer should likely already throw the type of error you want, which is also why axios or ky are a good idea. But that’s all speculative, people can do whatever they want inside the queryFn, doesn’t even have to be data fetching. So let’s remove this please

@leesb971204
Copy link
Contributor Author

@TkDodo

Thank you for the feedback! I’ve applied your suggestions.
Should I reflect this change in the other TypeScript docs as well (Vue, Solid, Angular)?
Interestingly, Vue Query doesn’t even mention a global Error type.

Copy link

nx-cloud bot commented Aug 18, 2025

View your CI Pipeline Execution ↗ for commit c66177a

Command Status Duration Result
nx affected --targets=test:sherif,test:knip,tes... ✅ Succeeded 52s View ↗
nx run-many --target=build --exclude=examples/*... ✅ Succeeded 1s View ↗

☁️ Nx Cloud last updated this comment at 2025-08-18 14:17:17 UTC

@TkDodo
Copy link
Collaborator

TkDodo commented Aug 18, 2025

yes please, you probably only need to change the examples

Copy link

pkg-pr-new bot commented Aug 18, 2025

More templates

@tanstack/angular-query-devtools-experimental

npm i https://pkg.pr.new/@tanstack/angular-query-devtools-experimental@9575

@tanstack/angular-query-experimental

npm i https://pkg.pr.new/@tanstack/angular-query-experimental@9575

@tanstack/eslint-plugin-query

npm i https://pkg.pr.new/@tanstack/eslint-plugin-query@9575

@tanstack/query-async-storage-persister

npm i https://pkg.pr.new/@tanstack/query-async-storage-persister@9575

@tanstack/query-broadcast-client-experimental

npm i https://pkg.pr.new/@tanstack/query-broadcast-client-experimental@9575

@tanstack/query-core

npm i https://pkg.pr.new/@tanstack/query-core@9575

@tanstack/query-devtools

npm i https://pkg.pr.new/@tanstack/query-devtools@9575

@tanstack/query-persist-client-core

npm i https://pkg.pr.new/@tanstack/query-persist-client-core@9575

@tanstack/query-sync-storage-persister

npm i https://pkg.pr.new/@tanstack/query-sync-storage-persister@9575

@tanstack/react-query

npm i https://pkg.pr.new/@tanstack/react-query@9575

@tanstack/react-query-devtools

npm i https://pkg.pr.new/@tanstack/react-query-devtools@9575

@tanstack/react-query-next-experimental

npm i https://pkg.pr.new/@tanstack/react-query-next-experimental@9575

@tanstack/react-query-persist-client

npm i https://pkg.pr.new/@tanstack/react-query-persist-client@9575

@tanstack/solid-query

npm i https://pkg.pr.new/@tanstack/solid-query@9575

@tanstack/solid-query-devtools

npm i https://pkg.pr.new/@tanstack/solid-query-devtools@9575

@tanstack/solid-query-persist-client

npm i https://pkg.pr.new/@tanstack/solid-query-persist-client@9575

@tanstack/svelte-query

npm i https://pkg.pr.new/@tanstack/svelte-query@9575

@tanstack/svelte-query-devtools

npm i https://pkg.pr.new/@tanstack/svelte-query-devtools@9575

@tanstack/svelte-query-persist-client

npm i https://pkg.pr.new/@tanstack/svelte-query-persist-client@9575

@tanstack/vue-query

npm i https://pkg.pr.new/@tanstack/vue-query@9575

@tanstack/vue-query-devtools

npm i https://pkg.pr.new/@tanstack/vue-query-devtools@9575

commit: c66177a

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🔭 Outside diff range comments (1)
docs/framework/solid/typescript.md (1)

155-159: Broken self-link: “Registering a global error” anchor is not defined in this page

This section links to #registering-a-global-error, but no such header exists in this file. Add the heading near the new augmentation snippet to avoid a dead intra-page link.

Apply this diff to introduce the missing section header and a short rationale just before the snippet marker:

- 
-[//]: # 'RegisterErrorType'
+## Registering a global error
+
+It’s often preferable to register a global default error type of `unknown`. This makes error handling explicit at call sites and avoids implying that all errors come from a specific client (e.g., Axios). Errors can also originate from `select`, memoized callbacks, or other userland code.
+
+[//]: # 'RegisterErrorType'
🧹 Nitpick comments (1)
docs/framework/solid/typescript.md (1)

134-151: Use ts fence (not tsx) for module augmentation snippet

There’s no JSX here. Using ts helps syntax highlighters and linters.

-```tsx
+```ts
 import '@tanstack/solid-query'
 
 declare module '@tanstack/solid-query' {
   interface Register {
     // Use unknown so call sites must narrow explicitly.
     defaultError: unknown
   }
 }
 
 const query = useQuery(() => ({
   queryKey: ['groups'],
   queryFn: fetchGroups,
 }))
 
 query.error
 //    ^? (property) error: unknown | null
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between ba4a117 and 84a63d8.

📒 Files selected for processing (1)
  • docs/framework/solid/typescript.md (2 hunks)
🔇 Additional comments (3)
docs/framework/solid/typescript.md (3)

139-141: Good call: defaultError: unknown removes misleading Axios coupling and enforces explicit narrowing

This aligns with the PR goal and is the safer recommendation.


150-150: LGTM: query.error becomes unknown | null as expected

Accurately reflects the global registration change and communicates the need for narrowing at call sites.


132-132: Snippet marker consistency verified across frameworks

I’ve checked all occurrences in the repo (Angular, Vue, React, Solid) and confirmed they all use the exact same single-quoted [//]: # 'RegisterErrorType' syntax with no deviations or alternate spellings. No changes are needed here.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
docs/framework/angular/typescript.md (1)

166-170: Consider adding a tiny narrowing example to demonstrate handling unknown.

A short follow-up snippet helps readers see how to safely narrow unknown at call sites without biasing towards any specific client:

computed(() => {
  const error = query.error()
  // error: unknown | null

  if (error) {
    if (error instanceof Error) {
      console.error(error.message) // safe access
    } else {
      // handle non-Error throwables (strings, objects, etc.)
      console.error(error)
    }
  }
})
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 84a63d8 and b675c8d.

📒 Files selected for processing (1)
  • docs/framework/angular/typescript.md (2 hunks)
🔇 Additional comments (2)
docs/framework/angular/typescript.md (2)

156-158: Good call: prefer unknown for Register.defaultError.

This aligns with the guidance that errors can originate from multiple places (not just the queryFn) and avoids misleading consumers into assuming Axios-specific errors globally.


151-160: Docs consistency check passed: No lingering defaultError: AxiosError usages
Verified across Angular, React, and Solid documentation—defaultError is uniformly set to unknown.

@leesb971204
Copy link
Contributor Author

@TkDodo

Solid didn’t have the [//]: # 'RegisterErrorType' section,
Vue didn’t have any example code at all,
and for Angular, only the example code needed to be updated.

all done! 🫡

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between b675c8d and c66177a.

📒 Files selected for processing (1)
  • docs/framework/vue/typescript.md (1 hunks)
🔇 Additional comments (1)
docs/framework/vue/typescript.md (1)

96-101: LGTM: Register augmentation to defaultError: unknown is correct and desirable

This matches TanStack Query’s global register pattern and avoids misleading framework-wide coupling to Axios. Good callout in the comment about forcing explicit narrowing at call sites.

Comment on lines +103 to +105
const { error } = useQuery({ queryKey: ['groups'], queryFn: fetchGroups })
// ^? const error: unknown | null
```
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

❓ Verification inconclusive

Fix Vue type hint: error is a Ref — show Ref<unknown | null> instead of unknown | null

In @tanstack/vue-query, fields returned from useQuery are Refs. The current hint drops the Ref wrapper and can confuse readers. It should be Ref<unknown | null>.

Apply this diff:

-//      ^? const error: unknown | null
+//      ^? const error: Ref<unknown | null>

Follow-up: Earlier in this page, the “TypingError” example shows Ref<unknown> (without | null). For consistency and accuracy, consider updating that hint to Ref<unknown | null> as well.


Fix Vue Query useQuery error type hint to use Ref

  • In docs/framework/vue/typescript.md at line 103, update the inferred type comment for error:
    -//      ^? const error: unknown | null
    +//      ^? const error: Ref<unknown | null>
  • Follow-up: earlier “TypingError” example currently shows Ref<unknown>—consider changing it to Ref<unknown | null> for consistency and accuracy.
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const { error } = useQuery({ queryKey: ['groups'], queryFn: fetchGroups })
// ^? const error: unknown | null
```
const { error } = useQuery({ queryKey: ['groups'], queryFn: fetchGroups })
// ^? const error: Ref<unknown | null>
🤖 Prompt for AI Agents
In docs/framework/vue/typescript.md around lines 103 to 105, the inline type
comment for the `error` returned from useQuery is incorrect: change the hint
from `const error: unknown | null` to `const error: Ref<unknown | null>` so it
reflects Vue's ref wrapper, and update the earlier “TypingError” example to use
`Ref<unknown | null>` instead of `Ref<unknown>` for consistency and accuracy.

@TkDodo TkDodo merged commit 2989e69 into TanStack:main Aug 18, 2025
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
documentation Improvements or additions to documentation
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants