我有一个 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);
}
在 JavaScript 中,您可以
throw
一切,而不仅仅是 Error
对象。一些例子:
throw 1;
throw "something";
throw [1, "something"];
throw { some: "thing" }
因此,在 TypeScript 中,
catch
总是会被输入为 unknown
,因为你不知道另一个函数调用实际上是什么 throw
n。无法保证它是一个 Error
实例。
您必须首先检查您实际拥有的内容 - 例如使用
instanceOf
运算符或 type 谓词函数。