0
0
Typescriptprogramming~10 mins

The in operator narrowing in Typescript - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
Ain
Binstanceof
ChasOwnProperty
Dtypeof
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.
2fill in blank
medium

Complete 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'
Ainstanceof
Bin
ChasOwnProperty
Dtypeof
Attempts:
3 left
💡 Hint
Common Mistakes
Using typeof which checks type, not property.
Using instanceof which is for class instances.
3fill in blank
hard

Fix 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'
Ain
BhasOwnProperty
Ctypeof
Dinstanceof
Attempts:
3 left
💡 Hint
Common Mistakes
Missing the 'in' keyword between property and object.
Using typeof or instanceof incorrectly.
4fill in blank
hard

Fill 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'
AhasOwnProperty
Btypeof
Cin
Dinstanceof
Attempts:
3 left
💡 Hint
Common Mistakes
Using typeof or instanceof instead of in.
Swapping the order of property and object.
5fill in blank
hard

Fill 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'
Ain
Canimal.meow
Danimal.bark
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.