Assume I have a type defined as follows:
type Result = {error:true,response: undefined} | {error:undefined, response:{nick:string}}
This type will either contain an error
property or a response
, but not both.
Now, I am attempting to create a function that can handle and narrow down this result
.
function unwrapResult<T extends {error: any}>(result:T) {
if(result.error){
throw result.error
}
return result
}
However, it seems like this function is not functioning as intended.
function test():Result {
return {error:undefined,response:{nick:'iki'}}
}
const data = unwrapResult(test())
data.response?.nick // response is {nick:string} | undefined
if(!data.error){
data.response.nick // this is ok
}
Is there a way to conditionally extract the response object so that I end up with just {response:{nick:string}}
without needing the if(!data.error)
check, which contradicts the purpose of the unwrapResult
function?