Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I handle 204 status with Typescript and fetch?

I'm trying to create post request using fetch and typescript. But can't create 204 status handler.

I have already tried to return promise with null value but it does't work.

    postRequest = async <T>(url: string, body: any): Promise<T> => {
        const response = await fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json;charset=utf-8'
            },
            body: JSON.stringify(body)
        });

        // here is my problem
        if (response.status === 204) {
            // error is: "Type 'null' is not assignable to type 'T'."
            return null;
            // I have tried to return promise, but it doesn't work.
            // error is: "Argument of type 'null' is not assignable to 
            // parameter of type 'T | PromiseLike<T> | undefined'."
            return new Promise(resolve => resolve(null));
        }

        if (!response.ok) {
            throw new Error(response.statusText);
        }

        return await response.json() as Promise<T>;
    };


    postRequest<{data: boolean}>('request', { someValue: 1234 });
like image 232
Artem Bochkarev Avatar asked Oct 16 '22 11:10

Artem Bochkarev


1 Answers

Use a Union Type to signal that either a Promise<T> or a Promise<null> gets returned:

postRequest = async <T>(url: string, body: any): Promise<T | null> => {

In this example, the return type is Promise<T | null>, which indicates that either T or null will be used for a resolved promise.

like image 115
Kirk Larkin Avatar answered Oct 31 '22 17:10

Kirk Larkin