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);
}
In JavaScript, you can
throweverything, not justErrorobjects. Some examples:So, in TypeScript, a
catchwill always be typedunknown, as you have no idea what was actuallythrown by another function call. There is no guarantee that it's anErrorinstance.You will have to check first what you actually have - for example using the
instanceOfoperator, or a type predicate function.