Complete the code to check if the property 'name' exists in the object.
if ('name' [1] obj) { console.log(obj.name); }
The in operator checks if a property exists in an object.
Complete the code to narrow the type using the in operator.
function printId(obj: { id: number } | { name: string }) {
if ('id' [1] obj) {
console.log(obj.id);
} else {
console.log(obj.name);
}
}The in operator narrows the type by checking if the property exists.
Fix the error in the type narrowing using the in operator.
function getValue(obj: { a: number } | { b: string }) {
if ('b' [1] obj) {
return obj.b;
}
return obj.a;
}The in operator requires the syntax: 'property' in object.
Fill the blank to correctly narrow types and access properties.
function describe(obj: { x: number } | { y: string }) {
if ('x' [1] obj) {
return obj.x.toFixed(2);
} else {
return obj.y.toUpperCase();
}
}The in operator is used as: 'property' in object to narrow types.
Fill both blanks to create a type guard using the in operator.
function isCat(animal: { meow: () => void } | { bark: () => void }): animal is { meow: () => void } {
return 'meow' [1] animal && typeof [2] === 'function';
}This function checks if 'meow' is a property of animal and if it is a function, to narrow the type.
