0
0
Typescriptprogramming~10 mins

Why instanceof fails on interfaces in Typescript - Test Your Understanding

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

Complete the code to check if 'obj' is an instance of class 'User'.

Typescript
if (obj [1] User) {
  console.log('It is a User');
}
Drag options to blanks, or click blank then click option'
Ainstanceof
Btypeof
Cin
Dequals
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'typeof' to check class instances.
Trying to use 'instanceof' with interfaces.
2fill in blank
medium

Complete the code to define an interface 'Person' with a 'name' property.

Typescript
interface Person {
  [1]: string;
}
Drag options to blanks, or click blank then click option'
Aage
Bname
Cid
Demail
Attempts:
3 left
💡 Hint
Common Mistakes
Using properties not defined in the interface.
Confusing property names.
3fill in blank
hard

Fix the error in the code that tries to use 'instanceof' with an interface.

Typescript
function checkPerson(obj: any) {
  if ('name' [1] obj) {
    console.log('Is a Person');
  }
}
Drag options to blanks, or click blank then click option'
Aequals
Btypeof
Cin
Dinstanceof
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to use 'instanceof' with interfaces.
Using 'typeof' to check for interface types.
4fill in blank
hard

Fill the blank to create a type guard function that checks if an object implements the 'Person' interface.

Typescript
function isPerson(obj: any): obj is Person {
  return [1] obj;
}
Drag options to blanks, or click blank then click option'
AhasOwnProperty
Bin
Cobj
D'name' in
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'hasOwnProperty' incorrectly.
Reversing the order of operands in the 'in' operator.
5fill in blank
hard

Fill all three blanks to create a safe type guard that checks if 'obj' implements 'Person' by verifying the 'name' property is a string.

Typescript
function isPerson(obj: any): obj is Person {
  return (typeof obj [1] 'object') [2] obj !== null && [3] in obj && typeof obj.name === 'string';
}
Drag options to blanks, or click blank then click option'
A&&
B===
C'name'
D||
Attempts:
3 left
💡 Hint
Common Mistakes
Using logical OR || instead of AND &&.
Checking property presence incorrectly.
Not verifying that 'obj' is not null.