0
0
Typescriptprogramming~10 mins

instanceof type guards 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 object is an instance of the class Dog.

Typescript
if (pet [1] Dog) {
  console.log("It's a dog!");
}
Drag options to blanks, or click blank then click option'
Aequals
Btypeof
Cin
Dinstanceof
Attempts:
3 left
💡 Hint
Common Mistakes
Using typeof instead of instanceof
Using in operator which checks properties, not types
2fill in blank
medium

Complete the function to return true if the pet is a Cat using instanceof.

Typescript
function isCat(pet: any): pet is Cat {
  return pet [1] Cat;
}
Drag options to blanks, or click blank then click option'
Ain
Binstanceof
Ctypeof
Dequals
Attempts:
3 left
💡 Hint
Common Mistakes
Using typeof which returns 'object' for objects
Using in which checks for properties, not types
3fill in blank
hard

Fix the error in the code to correctly check if vehicle is an instance of Truck.

Typescript
if (vehicle [1] Truck) {
  vehicle.loadCargo();
}
Drag options to blanks, or click blank then click option'
Ainstanceof
Btypeof
C===
D==
Attempts:
3 left
💡 Hint
Common Mistakes
Using == or === instead of instanceof
Using typeof which returns 'object' for objects
4fill in blank
hard

Fill both blanks to create a type guard that checks if pet is a Bird and calls fly().

Typescript
if (pet [1] Bird) {
  pet.[2]();
}
Drag options to blanks, or click blank then click option'
Ainstanceof
Brun
Cfly
Dwalk
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong operator like typeof
Calling a method not defined on Bird like walk or run
5fill in blank
hard

Fill all three blanks to create a type guard that checks if shape is a Circle and returns its radius.

Typescript
function getRadius(shape: Shape): number | null {
  if (shape [1] Circle) {
    return shape.[2];
  } else {
    return [3];
  }
}
Drag options to blanks, or click blank then click option'
Ainstanceof
Bradius
Cnull
Ddiameter
Attempts:
3 left
💡 Hint
Common Mistakes
Returning diameter instead of radius
Using typeof instead of instanceof
Returning 0 instead of null when not a Circle