Struggling to handle a 204 status response in my post request using fetch and typescript.
I've attempted to return a promise with a null value, but it's not working as expected.
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)
});
// I'm facing an issue here
if (response.status === 204) {
// error is: "Type 'null' is not assignable to type 'T'."
return null;
// I have tried returning a 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 });