I have a function that return object with two props (res, mes) where one of them is null:
const fetchJSON = <Res, Body>(link: string, body: Body): Promise<{ res: Res; mes: null } | { res: null; mes: Popup }> => {
return new Promise(resolve => {
fetch(link,
body: JSON.stringify(body)
})
.then(res => res.json())
.then((resJson: Res) => {
resolve({ res: resJson, mes: null })
})
.catch(err => {
resolve({ res: null, mes: { type: 'err', text: 'some error' } })
})
})
}
If after i use response of fetch without desctruction everything works fine:
const result = await fetchJSON<ResReaderData, ApiReaderData>('api/reader_data', { id })
if (result.mes) return popupPush(result.mes)
setProfile(result.res.reader)
But if i use object descruction:
const { res, mes } = await fetchJSON<ResReaderData, ApiReaderData>('api/reader_data', { readerId, role: 'alfa' })
if (mes) return popupPush(mes)
console.log(res.id)
Typescript doesn't understand that res is not null even if i checked mes:
Is there a way to fix this or i just need to forget about object destruction?
Or maybe there another approach for wrappers like this?
