You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何正确指定Promise返回类型?涉及UserType与ApiErrorType

解决方案

直接解决类型指定问题

你可以使用联合类型来指定Promise的返回类型,不需要修改原有UserType和ApiErrorType的定义,直接将二者组合即可:

const getUser = useMutation({
    mutationFn: async (data: CredentialType): Promise<UserType | ApiErrorType> => {
        try {
            const user: UserType = await original
                .post(`${isRegistration ? 'user/sign-up' : 'user/sign-in'}`, { json: data })
                .json();
            return user;
        } catch (error: any) {
            const errorJson: ApiErrorType = await error.response.json();
            return errorJson;
        }
    }
});

联合类型UserType | ApiErrorType明确表示这个Promise的结果要么是用户数据,要么是错误数据,完全符合你的业务逻辑,且不会污染原有类型定义。

更符合React Query设计的写法

不过需要注意:你当前在catch中返回错误的写法,不符合useMutation的常规设计。React Query的useMutation会自动捕获异步函数抛出的错误,并将其存储在mutation.error属性中,推荐的写法是抛出错误而非返回,同时通过泛型参数明确指定成功数据、错误数据和请求参数的类型:

// 明确指定useMutation的泛型参数:成功类型、错误类型、请求参数类型
const getUser = useMutation<UserType, ApiErrorType, CredentialType>({
    mutationFn: async (data) => {
        try {
            const user: UserType = await original
                .post(`${isRegistration ? 'user/sign-up' : 'user/sign-in'}`, { json: data })
                .json();
            return user;
        } catch (error: any) {
            const errorJson: ApiErrorType = await error.response.json();
            throw errorJson; // 抛出错误,交由useMutation处理
        }
    }
});

这种写法下:

  • getUser.data会被自动推断为UserType | undefined(仅成功时存在)
  • getUser.error会被自动推断为ApiErrorType | null(仅失败时存在)
  • 业务逻辑中可以直接通过getUser.isSuccess、getUser.isError状态判断,无需手动对返回值做类型校验,代码更清晰。

内容的提问来源于stack exchange,提问作者Vladislav

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 02:05:44