Middle
Task 7: There are Alien and Human types, combined into a Person type. Write a function checkAlien that checks if the given Person is an alien. Fix the TypeScript error when accessing the isAlien property.
sobes.tech AI
Answer from AI
In TypeScript, if you have a union type Person that can be either Alien or Human, and only Alien has the property isAlien, then directly accessing isAlien will result in an error because Human does not have such a property.
To fix this error, you should use a type guard — a check that allows the compiler to understand that the object is indeed an Alien.
Example:
type Alien = { isAlien: true; name: string };
type Human = { name: string };
type Person = Alien | Human;
function checkAlien(person: Person): boolean {
return 'isAlien' in person && person.isAlien === true;
}
Here, we use the in operator to check for the presence of the isAlien property. This allows TypeScript to narrow the type and avoid errors when accessing person.isAlien.
Alternatively, you can write a custom type guard:
type Alien = { isAlien: true; name: string };
type Human = { name: string };
type Person = Alien | Human;
function isAlien(person: Person): person is Alien {
return (person as Alien).isAlien === true;
}
function checkAlien(person: Person): boolean {
return isAlien(person);
}
This approach improves readability and reusability of the check.