0

I have a createAsyncThunk function. With status 401, I create a new error through the constructor and throw this error. In catch, why can't I get her message field? -> 'err' is of type 'unknown'.ts(18046)

export const add = createAsyncThunk<any, Product, { state: RootState }>(
    'product/addToCart',
    async (product, { getState, dispatch, rejectWithValue }) => {
        const response = await fetch(`${base_url}/main/wishlist/card`, {
            method: 'POST',
            body: JSON.stringify(product),
            headers: {
                Authorization: `Bearer ${getState().user.jwtToken}`,
                'Content-Type': 'application/json'
            }
        })
        try {
            if (response.ok) {
                const data = await response.json();
                console.log("Successful addition of a product to the wishlist");
                return data;
            }
            if (response.status === 400) {
                dispatch(refreshTokenRotation({}));
                dispatch(add(product));
            }
            if (response.status === 401) {
                throw new Error("Invalid or missing jwtToken");
            }
        }
        catch (err) {
            return rejectWithValue(err.message);//'err' is of type 'unknown'.ts(18046)
        }
    }
)

I tried adding the argument type but it didn't help

catch (error: Error) {
    console.log(error);
    return rejectWithValue(error.message);
}
yonatan_
  • 1
  • 1
  • `return rejectWithValue(error instanceof Error ? error.message : 'Unknown error')` – Meowster Jul 11 '23 at 12:58
  • maybe unrelated: since you are using redux-toolkit, maybe you could try its RTK Query which won't need to handle these logics – Jerryh001 Jul 11 '23 at 13:30

1 Answers1

0

In JavaScript, you can throw everything, not just Error objects. Some examples:

throw 1;
throw "something";
throw [1, "something"];
throw { some: "thing" }

So, in TypeScript, a catch will always be typed unknown, as you have no idea what was actually thrown by another function call. There is no guarantee that it's an Error instance.

You will have to check first what you actually have - for example using the instanceOf operator, or a type predicate function.

phry
  • 35,762
  • 5
  • 67
  • 81