redux 对象的类型为“未知”typescript

wmvff8tz  于 2023-08-05  发布在  TypeScript
关注(0)|答案(1)|浏览(170)

我有一个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);
}

aamkag61

aamkag611#

在JavaScript中,你可以throw所有东西,而不仅仅是Error对象。一些例子:

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

字符串
因此,在TypeScript中,catch将始终被键入unknown,因为您不知道另一个函数调用实际上是什么throw n。不能保证它是Error示例。
您必须首先检查您实际拥有的内容-例如使用instanceOf操作符或类型 predicate 函数。

相关问题