admin管理员组

文章数量:1323723

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 });

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 });
Share Improve this question asked Sep 14, 2019 at 20:11 Artem BochkarevArtem Bochkarev 1,36016 silver badges25 bronze badges 1
  • Two things, first you can wrap a value in a promise trivially by using the static method like so: Promise.resolve(null); so no need to call constructor. And undefined is a valid value per the error message, so unless you really need null you can always return Promise.resolve(undefined). – Jared Smith Commented Sep 14, 2019 at 20:50
Add a ment  | 

2 Answers 2

Reset to default 2

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.

If you want your function to return possibly null you have to add it to the return type.

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

And you don't need await the return value in an async function, the created promise already handles the awaiting for you:

return response.json() as T;

本文标签: javascriptHow can I handle 204 status with Typescript and fetchStack Overflow