I have a function that either returns an array if everything is ok or else returns an object with error = true and errMsg, how can I define the return type of my function
what I defined till now
searchFn: (value: string) => Promise< [] | { error: boolean } >;
the error is – Property ‘error’ does not exist on type ‘[] | { error: boolean; }’. Property ‘error’ does not exist on type ‘[]’ and Type ‘{ error: boolean; }’ is not assignable to type ‘[]’
My function –
const [data, setData] = useState([])
let result = await searchFn(id);
if (result?.error) {
log(result.error)
}
else {
log(result)
setData(result)
}
and my search function
const res = await fetch()
if (!res.ok) return { error: true, errMsg: errMsg };
return await res.json();
Am I doing this correctly, can you please help with the type definition of the searchFn
Thanks
2
Answers
this needs explicit type narrowing -
In your code, there are not any return, so, return type is
void