There is a function that returns an object with two properties (res, mes) where one of them could be 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' } })
})
})
}
Using the response of fetch without destructuring works perfectly fine:
const result = await fetchJSON<ResReaderData, ApiReaderData>('api/reader_data', { id })
if (result.mes) return popupPush(result.mes)
setProfile(result.res.reader)
However, when using object destructuring:
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 recognize that res is not null even after checking mes:
https://i.sstatic.net/gAu5S.png
Is there a way to fix this issue or should I avoid object destruction?
Alternatively, is there another approach for handling wrappers like this?