0
0
Typescriptprogramming~10 mins

Polymorphism through 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 an interface named Shape with a method area.

Typescript
interface Shape {
  [1](): number;
}
Drag options to blanks, or click blank then click option'
Asize
Barea
Ccalculate
Dperimeter
Attempts:
3 left
💡 Hint
Common Mistakes
Using method names unrelated to area like 'size' or 'perimeter'.
Forgetting to specify the return type.
2fill in blank
medium

Complete the class Circle to implement the Shape interface with the area method.

Typescript
class Circle implements Shape {
  radius: number;
  constructor(radius: number) {
    this.radius = radius;
  }
  [1](): number {
    return Math.PI * this.radius * this.radius;
  }
}
Drag options to blanks, or click blank then click option'
Aarea
BcalculateArea
CgetArea
Dsize
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different method name than the interface requires.
Not returning a number.
3fill in blank
hard

Fix the error in the Rectangle class so it correctly implements the Shape interface.

Typescript
class Rectangle implements Shape {
  width: number;
  height: number;
  constructor(width: number, height: number) {
    this.width = width;
    this.height = height;
  }
  [1](): number {
    return this.width * this.height;
  }
}
Drag options to blanks, or click blank then click option'
AcalculateArea
BgetArea
Carea
Dsize
Attempts:
3 left
💡 Hint
Common Mistakes
Using a method name different from the interface.
Misspelling the method name.
4fill in blank
hard

Fill both blanks to create a function that accepts any Shape and returns its area.

Typescript
function getArea([1]: [2]): number {
  return shape.area();
}
Drag options to blanks, or click blank then click option'
Ashape
BShape
Cany
Dobject
Attempts:
3 left
💡 Hint
Common Mistakes
Using a generic type like 'any' instead of the interface.
Using a non-descriptive parameter name.
5fill in blank
hard

Fill all three blanks to create an array of Shape objects and calculate the total area.

Typescript
const shapes: [1][] = [new Circle(5), new Rectangle(4, 6)];
let totalArea = 0;
for (const [2] of shapes) {
  totalArea += [3].area();
}
Drag options to blanks, or click blank then click option'
AShape
Bshape
DObject
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect type names like 'Object' instead of 'Shape'.
Using inconsistent variable names in the loop.