The object's type in typescript is identified as 'unknown'

When utilizing a createAsyncThunk function, I encountered an issue with retrieving the message field of an error when handling a status 401. The error is being treated as 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 attempted specifying the argument type but the issue persists.

catch (error: Error) {
    console.log(error);
    return rejectWithValue(error.message);
}

Answer №1

When working with JavaScript, it is important to remember that you can use the `throw` keyword for more than just throwing `Error` objects. Here are some examples:

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

In TypeScript, when catching errors, the type will always be `unknown` because you may not know what was actually thrown by another function call. It could be anything, not necessarily an `Error` instance.

To properly handle this situation, you would need to first check what type of object was thrown - for example, using the `instanceOf` operator or a type predicate function.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountered a Webpack error when trying to load the DomUtils module following the

I'm currently working on a project that involves TypeScript and React 0.14. I've set up my test environment using karma/mocha/chai, and it seems to be functioning well. However, when I try to import and use a function from enzyme, I encounter an ...

Why does the error message "AgGridModule is not exported by module ag-grid-ng2/main.js" appear when running npm run rollup?

Currently, I am working on creating the min.js file for my Angular 2 project using Tree shaking. Previously, I did not encounter any errors because I was not utilizing ag-grid. However, after running npm run rollup, an error is now being displayed in the c ...

Listening to events on the iterative variable of NgFor directive in Angular 2

Angular2 has been my latest exploration in solving a unique data binding challenge. In my UI, I've presented a javascript array of objects like a database recordset in an HTML table. Each row contains menus and inputs allowing users to modify the rec ...

Toggle visibility of content with the click of a button

Hey there, fellow coder! I'm still getting the hang of Angular 2 and Typescript, so please be patient with me as I learn. I am working on a project where I have 5 buttons that should toggle the visibility of content, similar to a side menu. Below is ...

Is there a universal method for monitoring user login status in React worldwide?

Many of my components change their behavior based on whether the user is currently logged in. A user is considered logged in if there is a valid jwt token stored locally. I could include an 'isLoggedIn' boolean in the states of all relevant com ...

What is the process of exporting a generator function in TypeScript?

Here is an example I have in JavaScript: export function* mySaga () { yield takeEvery('USER_FETCH_REQUESTED', fetchUser); } I'm wondering if it's possible to rewrite it as an arrow function in TypeScript, like the snippet below: ...

There seems to be a contradiction in my code - I am returning a Promise but TypeScript is throwing an error saying that the

I currently have a function that retrieves a bot's inventory on the Frontend fetchBotInventory() { this.socket.emit('fetch bot inv'); this.socket.on('bot inv', (botInventory) => { return new Promise((resolve, re ...

Enhance your React application by addressing and fixing minor issues

Whenever I input npm start while compiling the application to see changes, I consistently encounter minor errors such as: - Instead of <...ComponentName />, change it to ComponentName/> and similar instances to get rid of unnecessary spaces. I n ...

Unlocking the style within a .css file during an Angular unit test - here's how to do

I have been working on unit testing for an Angular app, specifically trying to access styles from a .css file within the unit test. I will share with you what I have attempted so far. component.listedIps.length=0; fixture.detectChanges(); let whitelis ...

Issue encountered while executing ./node_modules/.bin/cucumber-js within GitLab CI

I've encountered an issue while setting up a continuous integration build for my node project. Despite the fact that npm run test runs smoothly in my local setup, I am facing an exception in GitLab CI. The error arises from the following test command ...

ESLint Angular now identifies unused variables in type definitions

I've been updating and refining an Angular project (to Angular 8, Electron 6, Ionic 4) and we made the decision to transition from TSLint to ESLint. I've set up some rules and they're working fine, but I'm struggling to get rid of the ...

Playing around with Segment Analytics testing using Jest in TypeScript

I've been struggling to write a unit test that verifies if the .track method of Analytics is being called. Despite my efforts, the test keeps failing, even though invoking the function through http does trigger the call. I'm unsure if I've i ...

Error in Typescript: The type 'string' cannot be assigned to the type '"allName" | `allName.${number}.nestedArray`' within the react hook form

Currently, I am tackling the react hook form with typescript and facing a challenge with my data structure which involves arrays within an array. To address this, I decided to implement the useFieldArray functionality. allName: [ { name: "us ...

producing a NaN result when calling a reducer with an integer value

Could anyone assist me with this react-redux code? I have an input field that accepts numbers and adds them to the counter above. My goal is to reset the counter to 0 if the input is not a number, but currently when I type any character other than an int ...

What is the best way to determine the final letter of a column in a Google Sheet, starting from the first letter and using a set of

My current approach involves generating a single letter, but my code breaks if there is a large amount of data and it exceeds column Z. Here is the working code that will produce a, d: const countData = [1, 2, 3, 4].length; const initialLetter = 'A&a ...

Issue arises when fastify/websocket is being used and an argument of type '{ websocket: boolean; }' is not compatible or able to be assigned to a parameter

I am facing an issue with my new project that involves fastify and Typescript. The error I am encountering is as follows: Argument of type '{ websocket: boolean; }' is not assignable to parameter of type 'RouteShorthandOptions ...ts(2345) B ...

What is the best way to retrieve the `any` type when utilizing the `keyof` keyword?

I am struggling to articulate this question properly, so please refer to the code below interface TestParams<T> { order?: keyof T attr1?: number attr2?: string } async function Test<T = any>(_obj: TestParams<T>): Promise<T> { ...

Adding 30 Days to a Date in Typescript

Discovering Typescript for the first time, I'm attempting to calculate a date that is (X) months or days from now and format it as newDate below... When trying to add one month: const dateObj = new Date(); const month = dateObj.getUTCMonth() + 2; con ...

Assign a class to an Angular component's host element without any conditions

In my Angular project, I have a component where I need to apply a class unconditionally. To achieve this, the host property within the @Component decorator can be used: import { Component } from '@angular/core'; @Component({ selector: 'ap ...

Adjust the current type in order to allow all properties to become optional

Looking at the structure of my base type: type MyForm = { email: string; password: string; } I'm wondering if there's a possibility to change MyForm into this optional version: type MyFormOptional = { email?: string | null; password?: st ...