Im trying convert js code to ts, аnd i have this:
function api<T>(url: string): Promise<T> {
return fetch(url)
.then((res) => {
return res.json().then((resJson: T) => ({
ok: res.ok,
status: res.status,
body: resJson,
}));
})
.then((res) => {
if (res.ok) {
return res.body;
}
return Promise.reject({
status: res.status,
message: res.body.message,
});
});
}
I dont know how to solve the problem with
message: res.body.message // Property 'message' does not exist on type 'T'
My body-response contains the "message" property as an optional only if res.ok === false. How to solve this case? Approximate usage:
type ResBody = {
success: boolean;
message?: string;
data?: string[];
};
api<ResBody>("https://example.com")
.then(({ success, data }) => {
console.log(success, data);
})
.catch((err) => {
console.log(err.message, err.status)
});