3

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 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

1 Comment

Oh, Typescript, forcing me to type check my code... Thanks for your input!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.