My current scenario involves a server response containing a boolean indicating success and optional data or error information.
type ServerResponse = {
success: boolean;
data?: { [key: string]: string };
err?: { code: number, message: string };
}
Dealing with this type can sometimes feel cumbersome:
const resp: ServerResponse = await fetch(...);
if(resp.success) {
doSomething( resp.data?.foo );
} else {
handleErr( resp.err?.message );
}
It can be frustrating having to use the ?
operator when I know that data
will always exist when success === true
, and err
will always exist when success === false
.
I've tried understanding the mapped types documentation, but it doesn't seem to provide the solution I'm looking for.
Is changing the approach to ignore success
the only or best way to address this issue?
const resp: ServerResponse = await fetch(...);
if(resp.data) {
doSomething( resp.data.foo );
} else if(resp.err) {
handleErr( resp.err.message );
}
Although this method seems reasonable, I am interested in exploring more advanced typing techniques.