0
0
Typescriptprogramming~10 mins

Implementing interfaces in classes 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 declare that the class implements the interface.

Typescript
interface Animal {
  makeSound(): void;
}

class Dog implements Animal {
  makeSound() {
    console.log('Woof!');
  }
}
Drag options to blanks, or click blank then click option'
Ainherits
Bextends
Cuses
Dimplements
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'extends' instead of 'implements' for interfaces.
Forgetting to add the keyword before the interface name.
2fill in blank
medium

Complete the code to add a property from the interface to the class.

Typescript
interface Vehicle {
  wheels: number;
  drive(): void;
}

class Car implements Vehicle {
  [1]: number = 4;
  drive() {
    console.log('Driving');
  }
}
Drag options to blanks, or click blank then click option'
AwheelCount
Bwheels
CnumWheels
Dcount
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different property name than the interface.
Forgetting to declare the property at all.
3fill in blank
hard

Fix the error by completing the method signature to match the interface.

Typescript
interface Speaker {
  speak(words: string): void;
}

class Person implements Speaker {
  speak([1]) {
    console.log(words);
  }
}
Drag options to blanks, or click blank then click option'
Awords: string
Bwords
Cmessage: number
Dtext: string
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different parameter name.
Omitting the type annotation.
Using wrong type like number instead of string.
4fill in blank
hard

Fill both blanks to complete the class implementing the interface with a constructor.

Typescript
interface User {
  name: string;
  age: number;
}

class Member implements User {
  [1]: string;
  [2]: number;

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }
}
Drag options to blanks, or click blank then click option'
Aname
Busername
Cage
Dyears
Attempts:
3 left
💡 Hint
Common Mistakes
Using different property names than the interface.
Forgetting to declare both properties.
5fill in blank
hard

Fill all three blanks to implement the interface with a method and property.

Typescript
interface Logger {
  level: string;
  log(message: string): void;
}

class ConsoleLogger implements Logger {
  [1]: string = 'info';

  [2](message: string): void {
    console.log(`[$[3]] ${message}`);
  }
}
Drag options to blanks, or click blank then click option'
Alevel
Blog
Cthis.level
Dmessage
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong property or method names.
Not using this to access the property inside the method.
Missing the method parameter.