In typescript, is there a way to use a value in object that the key may not exist?

Viewed 33

I'm using the example in the redux doc:

const axiosBaseQuery: BaseQueryFn<
    {
        url: string;
        method: "get" | "put" | "post" | "delete";
        data?: AxiosRequestConfig["data"];
    },
    unknown,
    unknown
> = async (args, api, extraOptions) => {
    try {
        const axiosInstance = initializeAxios(api.getState() as RootState);

        const result = await axiosInstance[args.method]("api/v0/" + args.url, args.data);

        return { data: result.data };
    } catch (axiosError) {
        const err = axiosError as AxiosError;

        return {
            error: { status: err.response?.status, data: err.response?.data }
        };
    }
};

Now after calling my API, my response type would be {data:string}|{error:unknown} and when I use response?.data I receive data does not exist in {error:unknown}

If you have any idea on how to fix it, let me know!

0 Answers
Related