0

I have an async-await handler:

const asyncHandler = async <Type>(
  promise: Promise<Type>
): Promise<[Type, null] | [null, string]> => {
  try {
    const response = await promise
    return [response, null]
  } catch (error) {
    console.log(error)
    return [null, error]
  }
}

export default asyncHandler

This give me no error:

import asyncHandler from './async_handler'

interface Success {
  payload: string
}

interface MyError {
  payload: undefined
  error?: true
}

const fetchData = async (): Promise<Success | MyError> => {
  const fetchDataResponse = await asyncHandler<string>(
    new Promise((resolve) => {
      setTimeout(() => resolve('potato'), 200)
    })
  )

  if (fetchDataResponse[1]) return { payload: undefined, error: true }

  return { payload: fetchDataResponse[0] }
}

export default fetchData

but this give type error because is expecting response to be string or undefined but response is string or null

import asyncHandler from './async_handler'

interface Success {
  payload: string
}

interface MyError {
  payload: undefined
  error?: true
}

const fetchData = async (): Promise<Success | MyError> => {
  const [response, error] = await asyncHandler<string>(
    new Promise((resolve) => {
      setTimeout(() => resolve('potato'), 200)
    })
  )

  if (error) return { payload: undefined, error: true }

  return { payload: response } // Type 'string | null' is not assignable to type 'string | undefined'. Type 'null' is not assignable to type 'string | undefined'.ts(2322)
}

export default fetchData

I know that response is not set only to string type because those two variables are independent now but is there a way to make the second example work like the first one?

2
  • Just a suggestion - you should use console.error() instead of console.log() in your catch block Commented Jul 5, 2021 at 19:41
  • Wow, thanks. I'll use! :D Commented Jul 5, 2021 at 19:44

2 Answers 2

0

Found that this is expected! https://github.com/microsoft/TypeScript/issues/32639

Related answer: Typescript type fails if object is destructed

Sign up to request clarification or add additional context in comments.

Comments

0

You need to check fetchDataResponse[0] for null

Next as you described you interface MyError, payload can be only undefined. For interface Success, payload can be only string, but you want to return response which can be string or null

Making payload optional, you will achieve what you want

interface MyError {
  payload?: null
  error?: true
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.