vue.js 失败的useMutation请求的TypeScript类型是什么?

ne5o7dgx  于 2023-05-07  发布在  Vue.js
关注(0)|答案(3)|浏览(131)

下面是一个例子:

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?
    ...
  }
})

我想用它的TypeScript类型注解catch(e)的e参数-但是它是什么类型呢?如果你知道解决方案,如果可能的话,也解释一下我是如何自己解决的,谢谢!

nr7wwzry

nr7wwzry1#

在快速查看函数的source code之后,它似乎抛出了一个ApolloError,根据this answer,可以从客户端导入:

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

解释一下我自己是怎么发现的
基本上只要看看函数可能抛出什么,然后找出如何导入它(stackoverflow在这里真的很有帮助)。当然,只有当其他包也是用typescript编写的时候,这才有效。否则,最好的选择可能是使用Error

5lhxktic

5lhxktic2#

查看apollo的代码,类型为ApolloError
https://github.com/vuejs/apollo/blob/526fbacc18861029494963d03a88d7995f1cfc1f/packages/vue-apollo-composable/src/util/toApolloError.ts#L4
你可以尝试这两种策略来推断类型

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  {  
  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
}
7rfyedvj

7rfyedvj3#

const {
mutate: storeData,
} = useMutation<TDate, TError>(...) // 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?
    ...
  }
})

传递数据类型和错误响应类型。或者在storeData()中执行

相关问题