0
0
Typescriptprogramming~10 mins

Merging classes with interfaces 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 a class that implements an interface.

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

class Employee implements [1] {
  constructor(public name: string, public age: number) {}
}
Drag options to blanks, or click blank then click option'
APerson
BEmployee
CObject
DInterface
Attempts:
3 left
💡 Hint
Common Mistakes
Using the class name instead of the interface name in the implements clause.
Trying to implement a non-interface type.
2fill in blank
medium

Complete the code to merge a class and an interface with the same name.

Typescript
interface User {
  id: number;
}

class [1] {
  constructor(public id: number, public name: string) {}
}
Drag options to blanks, or click blank then click option'
APerson
BUser
CCustomer
DEmployee
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different name for the class than the interface.
Not understanding that merging requires the same name.
3fill in blank
hard

Fix the error in the merged class and interface by completing the code.

Typescript
interface Product {
  price: number;
}

class Product {
  constructor(public price: number, public name: string) {}
  getPrice() {
    return this.[1];
  }
}
Drag options to blanks, or click blank then click option'
Aprice
Bcost
Cname
Dvalue
Attempts:
3 left
💡 Hint
Common Mistakes
Returning a property that does not exist.
Confusing property names.
4fill in blank
hard

Fill both blanks to add a method to the interface and implement it in the class.

Typescript
interface Vehicle {
  speed: number;
  [1](): string;
}

class Vehicle {
  constructor(public speed: number) {}
  [2]() {
    return `Speed is ${this.speed} km/h`;
  }
}
Drag options to blanks, or click blank then click option'
AgetSpeed
Bspeed
CgetSpeed()
Dspeed()
Attempts:
3 left
💡 Hint
Common Mistakes
Omitting parentheses in interface method declaration.
Mismatch between interface and class method names.
5fill in blank
hard

Fill all three blanks to merge an interface and class, adding a property and method.

Typescript
interface Book {
  title: string;
  [1](): string;
}

class Book {
  constructor(public title: string, public author: string) {}
  [2]() {
    return `${this.title} by ${this.author}`;
  }
  [3]: number = 2024;
}
Drag options to blanks, or click blank then click option'
AgetDetails()
BgetDetails
CpublishedYear
Dpublished
Attempts:
3 left
💡 Hint
Common Mistakes
Not matching method names exactly between interface and class.
Using inconsistent property names.