Need help returning an object as a fetch response with either the property "data" or "mes":
{ data: Data } | { mes: ErrMessage }
Having trouble with TypeScript complaining about this object, let's call it props:
if (prop.mes) return // Property 'mes' does not exist on type '{ data: string; }'.
prop.data // Property 'data' does not exist on type '{ mes: string; }'.
Is there a better alternative than defining a large type in the component each time?
{ data: Data, mes: false } | { mes: ErrMessage, data: false}
Check out the example on Typescript playground here.
type ErrMessage = string // some complex structure
const fetchAPI = <Body = any, Data = any>(link: string, body: Body): Promise<{ data: Data } | { mes: ErrMessage }> => {
return new Promise((resolve) => {
fetch(link, { body: JSON.stringify(body) })
.then((raw) => raw.json())
.then((res) => {
resolve(res.err ? { mes: res.err } : { data: res })
})
.catch((err) => {
resolve({ mes: 'text' })
})
})
}
type Data = string // some complex structure
type MyReq = string // some complex structure
type MyRes = {data: Data } | {mes: ErrMessage}
const someLoader = async () => {
const res = await fetchAPI<MyReq, MyRes>('reader', 'body')
return {res}
}
const componentThatGetProp = (prop: MyRes ) => {
// error handler
if (prop.mes) return // Property 'mes' does not exist on type '{ data: string; }'.
// do something
prop.data // Property 'data' does not exist on type '{ mes: string; }'.
}