我试图以一种类型安全的方式从第一个错误中获得message
分:
// In a real case this is returned from the 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
);
// "sources" is typed as "false | object | null"
const errors = (
typeof sources === 'object'
&& sources
&& 'errors' in sources
&& Array.isArray(sources.errors)
&& sources.errors
);
// "errors" is typed as "false | any[] | null"
const firstError = errors && errors[0];
// "firstError" is typed as "any"
const message = (
typeof firstError === 'object'
&& firstError
&& 'message' in firstError
&& typeof firstError.message === 'string'
&& firstError.message
);
但由于某些原因,message
最终变成了any
,并且找不到方法.
我做错了什么?
判断一下这个TS Playground.