Object is of type 'unknown' typescript

592 views Asked by At

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);
}
1

There are 1 answers

0
phry On

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.