When using the lib, the error is always unknown which throws an error in strict mode. I'm wondering what the best way to set what the error could be or if we should be allowing the passing of a Error type? https://github.com/DefinitelyTyped/DefinitelyTyped/blob/1c407ae2c824d695b9e1a8257c0a5c67fad2f98d/types/react-query/index.d.ts#L205
@Igorbek
@ericchernuka thanks for asking. That was intentional. The library does not guarantee the type of error in case of an error. We have discussed this in the PR: https://github.com/DefinitelyTyped/DefinitelyTyped/pull/43438#pullrequestreview-383665192, you can take a look.
So basically, a caught exception can be anything, including but not limited to Error, such as primitives and even null or undefined.
Libraries usually choose between using any or unknown. In my opinion, using unknown is safer.
Ok. Probably not the place to ask, but what鈥檚 the best practice to type this?
I'd suggest adding a type test function:
function isError(error: unknown): error is Error {
return error instanceof Error;
}
...
const { data, error, status } = useQuery(...)
if (status === 'error') {
if (isError(error)) {
// handle Error
error.message // ok
} else {
// handle unknown error
}
}
Most helpful comment
I'd suggest adding a type test function: