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?
console.error()instead ofconsole.log()in yourcatchblock