Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to check if the property 'name' exists in the object.
Typescript
if ('name' [1] obj) { console.log(obj.name); }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using typeof instead of in.
Using hasOwnProperty as a keyword instead of a method.
Using instanceof which checks object type, not properties.
✗ Incorrect
The in operator checks if a property exists in an object.
2fill in blank
mediumComplete the code to narrow the type using the in operator.
Typescript
function printId(obj: { id: number } | { name: string }) {
if ('id' [1] obj) {
console.log(obj.id);
} else {
console.log(obj.name);
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using typeof which checks type, not property.
Using instanceof which is for class instances.
✗ Incorrect
The in operator narrows the type by checking if the property exists.
3fill in blank
hardFix the error in the type narrowing using the in operator.
Typescript
function getValue(obj: { a: number } | { b: string }) {
if ('b' [1] obj) {
return obj.b;
}
return obj.a;
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Missing the 'in' keyword between property and object.
Using typeof or instanceof incorrectly.
✗ Incorrect
The in operator requires the syntax: 'property' in object.
4fill in blank
hardFill the blank to correctly narrow types and access properties.
Typescript
function describe(obj: { x: number } | { y: string }) {
if ('x' [1] obj) {
return obj.x.toFixed(2);
} else {
return obj.y.toUpperCase();
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using typeof or instanceof instead of in.
Swapping the order of property and object.
✗ Incorrect
The in operator is used as: 'property' in object to narrow types.
5fill in blank
hardFill both blanks to create a type guard using the in operator.
Typescript
function isCat(animal: { meow: () => void } | { bark: () => void }): animal is { meow: () => void } {
return 'meow' [1] animal && typeof [2] === 'function';
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'bark' instead of 'meow' in the check.
Not checking the type of the property.
Using typeof on the object instead of the property.
✗ Incorrect
This function checks if 'meow' is a property of animal and if it is a function, to narrow the type.