React-Query mutation.error not recognized as type Error

Viewed 2754

When using a React-Query mutation, I have a component that displays an error message. but Typescript doesn't recognize the mutation.error property as type Error:

if (mutation.isError){
    console.log(mutation.error.message);             // Property 'message' does not exist on type 'unknown'.
    console.log((mutation.error as Error).message);  // works
}

How can I inform typescript that mutation.error is indeed an Error object?

1 Answers

You’d have to provide the generics to useMutation:

useMutation<MyData, Error>

But I wouldn’t do that. Errors are unknown because at runtime, also non-error objects can be thrown.

I think the easiest solution is to perform an instanceof check instead of checking for isError:

if (mutation.error instanceof Error){
    console.log(mutation.error.message);
}

This will correctly narrow the type of error so that .message is available

Related