Trying to extract the message
from the first error in a type-safe manner:
// Data returned from backend
const mutationError: unknown = {
sources: {
errors: [
{
message: 'Hello from error message'
}
]
}
};
const sources = (
typeof mutationError === 'object'
&& mutationError
&& 'sources' in mutationError
&& typeof mutationError.sources === 'object'
&& mutationError.sources
);
const errors = (
typeof sources === 'object'
&& sources
&& 'errors' in sources
&& Array.isArray(sources.errors)
&& sources.errors
);
const firstError = errors && errors[0];
const message = (
typeof firstError === 'object'
&& firstError
&& 'message' in firstError
&& typeof firstError.message === 'string'
&& firstError.message
);
However, the variable message
is wrongly typed as any
. What could be the issue?
Explore more on this TS Playground.