我有一个createAsyncThunk函数。对于状态401,我通过构造函数创建一个新的错误并抛出此错误。在catch中,为什么我不能得到她的消息字段?-> 'err'的类型为'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)
}
}
)
字符串
我尝试添加参数类型,但没有帮助
catch (error: Error) {
console.log(error);
return rejectWithValue(error.message);
}
型
1条答案
按热度按时间aamkag611#
在JavaScript中,你可以
throw
所有东西,而不仅仅是Error
对象。一些例子:字符串
因此,在TypeScript中,
catch
将始终被键入unknown
,因为您不知道另一个函数调用实际上是什么throw
n。不能保证它是Error
示例。您必须首先检查您实际拥有的内容-例如使用
instanceOf
操作符或类型 predicate 函数。