skip to Main Content

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


  1. Chosen as BEST ANSWER

    this needs explicit type narrowing -

    if (typeof result === "object" && !Array.isArray(result)) {
      if (result?.error) {
         log(result.error)
      }
    } else {
      if (Array.isArray(result)) {
        setData(result);
      }
    }
    

  2. In your code, there are not any return, so, return type is void

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search