I have a situation where I need to handle either an object of type Person or an Error being returned by a function. My goal is to read the values of keys in the returned object only if it's not an Error.
The code snippet below throws an error on the last line:
Property 'firstName' does not exist on type 'Person | Error'
You can view the error at this link.
interface Person {
firstName: string;
lastName: string;
}
function greeter(person: Person): Person | Error {
if (person.firstName === 'Malcolm') {
return new Error('This firstName is not allowed');
}
return {
firstName: person.firstName,
lastName: person.lastName,
};
}
const x = greeter({
firstName: "Malcolm",
lastName: "Reynolds",
});
const { firstName, lastName } = x;
In certain cases, I must return an Error. It cannot be skipped.
Thank you for your assistance!