Search code examples
typescriptnext.jsantdredux-toolkitrtk-query

How to remove 'loginError.data' is of type 'unknown' error?


I am new to typescript and trying out nextjs and rtk query with antd. By when trying to access error in useLoginMutation inside properties error.data.message , it shows error.data is type unknown .

What I have tried so far is I used a type guard function.

import { FetchBaseQueryError } from "@reduxjs/toolkit/dist/query";

export default function isFetchBaseQueryError(
    error: unknown
): error is FetchBaseQueryError {
    return typeof error === "object" && error != null && "status" in error;
}
if (!isLoginLoading && error) {
    if (isFetchBaseQueryError(error)) {
        notification.error({
            message: "Login Failed",
            description: error.data.message, // this line is causing error
        });
    }
}

Solution

  • Take a look at this one: https://codesandbox.io/s/icy-fire-hsjoqx?file=/src/App.tsx

    import get from 'lodash/get'
    
    function isFetchBaseQueryError(
      error: unknown
    ): error is FetchBaseQueryError & { data: { message: string } } {
      return (
        typeof error === "object" &&
        error != null &&
        "status" in error &&
        "data" in error &&
        !!get(error, "data.message") // make sure data.message exists
      );
    }
    
    const error = { data: { message: "message" }, status: "403" };
    if (isFetchBaseQueryError(error)) {
      console.log(error.data.message);
    }
    
    const error1 = { status: "403" };
    if (isFetchBaseQueryError(error1)) {
      console.log(error.data.message);
    } else {
      console.log("data.message not defined");
    }