0
0
Typescriptprogramming~10 mins

Extending classes with types 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 extend the base class correctly.

Typescript
class Animal {
  name: string;
  constructor(name: string) {
    this.name = name;
  }
}

class Dog extends [1] {
  bark() {
    return `Woof! I am ${this.name}`;
  }
}
Drag options to blanks, or click blank then click option'
AAnimal
BDog
CCat
DPet
Attempts:
3 left
💡 Hint
Common Mistakes
Extending the same class (Dog) instead of the base class (Animal).
Using a class name that does not exist.
2fill in blank
medium

Complete the code to add a type to the extended class property.

Typescript
class Vehicle {
  wheels: number;
  constructor(wheels: number) {
    this.wheels = wheels;
  }
}

class Car extends Vehicle {
  model: [1];
  constructor(wheels: number, model: string) {
    super(wheels);
    this.model = model;
  }
}
Drag options to blanks, or click blank then click option'
Anumber
Bstring
Cboolean
Dany
Attempts:
3 left
💡 Hint
Common Mistakes
Using number or boolean for a text property.
Using any when a specific type is better.
3fill in blank
hard

Fix the error in the constructor to call the parent class correctly.

Typescript
class Person {
  age: number;
  constructor(age: number) {
    this.age = age;
  }
}

class Employee extends Person {
  salary: number;
  constructor(age: number, salary: number) {
    [1];
    this.salary = salary;
  }
}
Drag options to blanks, or click blank then click option'
Asuper(age);
Bsuper.salary = salary;
Cthis.age = age;
Dsuper();
Attempts:
3 left
💡 Hint
Common Mistakes
Calling super() without arguments causes an error.
Trying to assign super.salary which is invalid.
4fill in blank
hard

Fill both blanks to create a generic class that extends another generic class.

Typescript
class Box<T> {
  content: T;
  constructor(content: T) {
    this.content = content;
  }
}

class ColoredBox<[1]> extends Box<[2]> {
  color: string;
  constructor(content: [2], color: string) {
    super(content);
    this.color = color;
  }
}
Drag options to blanks, or click blank then click option'
AT
BU
DV
Attempts:
3 left
💡 Hint
Common Mistakes
Using different generic type parameters in subclass and superclass.
Not specifying generic types in the subclass.
5fill in blank
hard

Fill all three blanks to extend an interface with a class and add a new method.

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

class ConsoleLogger implements [1] {
  [2](message: string): void {
    console.log(message);
  }
  [3](): void {
    console.log('Logging complete');
  }
}
Drag options to blanks, or click blank then click option'
ALogger
Blog
Cfinish
DLoggerInterface
Attempts:
3 left
💡 Hint
Common Mistakes
Using a wrong interface name in implements.
Misspelling the method names.
Not implementing the required interface method.