What is the TypeScript type of failed useMutation requests?

Viewed 226

Consider the following code:

const {
  mutate: storeData,
} = useMutation(...) // useMutation from @vue/apollo-composable

const sendForm = handleSubmit(async (values) => {
  try {
    const result = await storeData()
    console.log(result)
  } catch (e) { // <---- what is the TypeScript type of e?
    ...
  }
})

I want to annotate the e parameter of catch(e) with its TypeScript type - but which type is it? If you know the solution, if possible also explain how I could have figured that out myself, thanks!

2 Answers

After having a quick look at the source code of the function, it seems like it throws an ApolloError, which, according to this answer, can be imported from the client:

import { ApolloError } from '@apollo/client/errors';

explain how I could have figured that out myself

Basically just have a look at what the function might throw and after that find out how to import it (stackoverflow can be really helpful here). Of course this only works if the other package is also written in typescript. Otherwise the best option is probably to use Error.

Inspecting the code of apollo, the type is ApolloError

https://github.com/vuejs/apollo/blob/526fbacc18861029494963d03a88d7995f1cfc1f/packages/vue-apollo-composable/src/util/toApolloError.ts#L4

You can try thees two stategies to infer the type

import { ApolloError, isApolloError } from '@apollo/client/core'
import { GraphQLErrors } from '@apollo/client/errors'

export function toApolloError (error: unknown): ApolloError {
  if (!(error instanceof Error)) {
    return new ApolloError({
      networkError: Object.assign(new Error(), { originalError: error }),
      errorMessage: String(error),
    })
  }

  if (isApolloError(error)) {
    return error
  }

  return new ApolloError({ networkError: error, errorMessage: error.message })
}

export function resultErrorsToApolloError (errors: GraphQLErrors): ApolloError {
  return new ApolloError({
    graphQLErrors: errors,
    errorMessage: `GraphQL response contains errors: ${errors.map((e: any) => e.message).join(' | ')}`,
  })
}

Try something like this:

try  {  
  const result = await storeData()
  console.log(result)  
}  catch  (error: ApolloError)  {  
  // your stuff
}

// or
 
try  {  
  const result = await storeData()
  console.log(result)  
}  catch  (error)  { 
if (error instanceof ApolloError) {
 
  // your stuff
}else {
  // other stuff
}
Related