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 });
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With