【发布时间】:2019-12-11 02:41:28
【问题描述】:
我有一个函数返回带有两个道具(res,mes)的对象,其中一个为空:
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' } })
})
})
}
如果在我使用 fetch 的响应而不进行破坏之后一切正常:
const result = await fetchJSON<ResReaderData, ApiReaderData>('api/reader_data', { id })
if (result.mes) return popupPush(result.mes)
setProfile(result.res.reader)
但是如果我使用对象分解:
const { res, mes } = await fetchJSON<ResReaderData, ApiReaderData>('api/reader_data', { readerId, role: 'alfa' })
if (mes) return popupPush(mes)
console.log(res.id)
即使我检查了 mes,Typescript 也不明白 res 不为空:
有没有办法解决这个问题,或者我只需要忘记对象破坏?
或者也许还有其他方法可以用于这样的包装器?
【问题讨论】:
标签: typescript