user14367514
user14367514

Reputation:

I Keep getting, 'Object is of type 'unknown'' error

I'm trying to use a switch statement to notify the client side of any errors

axios.interceptors.response.use(response => {
    return response
}, (error: AxiosError) => {
    const {data, status} = error.response!;
    switch (status) {
        case 400:
            toast.error(data.title);
            break;
        case 401:
            toast.error(data.title);
            break;
        case 500:
            toast.error(data.title);
            break;
    
        default:
            break;
    }
    return Promise.reject(error.response);
})

But it complains about the 'data' variable, saying 'Object is of type 'unknown'. After doing some research they said I have to use a type guard, but I don't believe type guards are available for switch statements. Does anyone know how to rewrite this as an if statement or knows what I can do to fix this ?

Upvotes: 2

Views: 426

Answers (2)

Ravidf
Ravidf

Reputation: 19

Me too got same issues and found the solution. This is working for me.

const {data, status} = error.response!;

Working code:

const {data, status}:any = error.response!;

Upvotes: 2

Micky
Micky

Reputation: 572

Does marking it as optional and defaulting the value get rid of the error?

const {data? = null, status} = error.response!;

Upvotes: 0

Related Questions