Bird
Raised Fist0
Typescriptprogramming~10 mins

Implementing interfaces in classes in Typescript - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Implementing interfaces in classes
Define Interface
↓
Create Class
↓
Implement Interface in Class
↓
Add Required Properties/Methods
↓
Create Class Instance
↓
Use Instance with Interface Contract
This flow shows how a class follows a blueprint (interface) by adding required parts, then creating and using an instance.
Execution Sample
Typescript
interface Animal {
  name: string;
  makeSound(): void;
}

class Dog implements Animal {
  name: string = "Buddy";
  makeSound() { console.log("Woof!"); }
}

const pet = new Dog();
pet.makeSound();
Defines an interface Animal, a class Dog that follows it, then creates a Dog and calls its sound.
Execution Table
StepActionEvaluationResult
1Define interface Animal with name and makeSound()Interface createdAnimal interface ready
2Create class Dog implementing AnimalClass Dog must have name and makeSound()Dog class created with interface contract
3Set Dog.name = "Buddy"Property assignedDog.name = "Buddy"
4Define Dog.makeSound() to print "Woof!"Method assignedDog.makeSound() ready
5Create instance pet = new Dog()Object createdpet is Dog with name "Buddy"
6Call pet.makeSound()Execute methodOutput: Woof!
7End of programNo more actionsExecution stops
💡 Program ends after calling makeSound() on pet instance
Variable Tracker
VariableStartAfter Step 3After Step 5Final
Dog.nameundefined"Buddy""Buddy""Buddy"
petundefinedundefinedDog instanceDog instance
Key Moments - 3 Insights
Why does the class Dog have to include both name and makeSound()?
Because Dog implements the Animal interface, it must have all properties and methods defined in Animal, as shown in execution_table steps 2-4.
What happens if Dog does not implement makeSound()?
TypeScript will give an error at step 2 because the class does not fulfill the interface contract.
Why can we call pet.makeSound() without errors?
Because pet is an instance of Dog which implements Animal, so makeSound() is guaranteed to exist (see execution_table step 6).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of Dog.name after step 3?
A"Buddy"
Bundefined
Cnull
D"Dog"
💡 Hint
Check the variable_tracker row for Dog.name at After Step 3
At which step is the pet instance created?
AStep 6
BStep 3
CStep 5
DStep 2
💡 Hint
Look at execution_table step descriptions for object creation
If Dog did not implement makeSound(), what would happen?
AProgram runs normally
BTypeScript error at class definition
CError only when calling makeSound()
DNo error, but makeSound() prints nothing
💡 Hint
Refer to key_moments about interface contract enforcement
Concept Snapshot
interface InterfaceName {
  property: type;
  method(): returnType;
}

class ClassName implements InterfaceName {
  property = value;
  method() { /* code */ }
}

- Class must have all interface members.
- Ensures consistent structure.
- Use instances to access implemented members.
Full Transcript
This example shows how to use interfaces in TypeScript. First, we define an interface Animal with a name and a makeSound method. Then, we create a class Dog that implements Animal, so it must have a name property and a makeSound method. We assign the name "Buddy" and define makeSound to print "Woof!". Next, we create an instance pet of Dog and call pet.makeSound(), which outputs "Woof!". The execution table traces each step, showing how the class follows the interface contract and how the instance behaves. The variable tracker shows how Dog.name and pet change during execution. Key moments clarify why the class must implement all interface members and what happens if it doesn't. The quiz tests understanding of variable values, instance creation, and interface enforcement. The snapshot summarizes the syntax and rules for implementing interfaces in classes.

Practice

(1/5)
1. What does the implements keyword do in a TypeScript class?
easy
A. It ensures the class follows the structure defined by an interface.
B. It creates a new interface inside the class.
C. It imports an interface from another file.
D. It automatically generates methods for the class.

Solution

  1. Step 1: Understand the role of interfaces

    Interfaces define a contract of properties and methods that a class must have.
  2. Step 2: Role of implements keyword

    The implements keyword makes sure the class follows that contract exactly.
  3. Final Answer:

    It ensures the class follows the structure defined by an interface. -> Option A
  4. Quick Check:

    implements enforces interface structure [OK]
Hint: Remember: implements means 'follow the interface rules' [OK]
Common Mistakes:
  • Thinking implements creates or imports interfaces
  • Believing implements auto-generates code
  • Confusing implements with extends
2. Which of the following is the correct syntax to make a class Car implement an interface Vehicle?
easy
A. interface Car implements Vehicle {}
B. class Car implements Vehicle {}
C. class Car extends Vehicle {}
D. class Car uses Vehicle {}

Solution

  1. Step 1: Identify correct keywords for class and interface

    Classes use the keyword implements to follow interfaces.
  2. Step 2: Check syntax correctness

    class Car implements Vehicle {} is the correct way to declare this.
  3. Final Answer:

    class Car implements Vehicle {} -> Option B
  4. Quick Check:

    Class uses implements for interfaces [OK]
Hint: Use 'implements' keyword after class name for interfaces [OK]
Common Mistakes:
  • Using extends instead of implements for interfaces
  • Trying to implement interface in interface declaration
  • Using 'uses' keyword which doesn't exist
3. What will be the output of this code?
interface Animal {
  name: string;
  speak(): string;
}

class Dog implements Animal {
  name: string;
  constructor(name: string) {
    this.name = name;
  }
  speak() {
    return `${this.name} says woof`;
  }
}

const dog = new Dog('Buddy');
console.log(dog.speak());
medium
A. undefined
B. "Dog says woof"
C. "Buddy says woof"
D. Error: Dog does not implement speak()

Solution

  1. Step 1: Check class implements interface correctly

    Dog class has property name and method speak() as required.
  2. Step 2: Understand method output

    speak() returns a string with the dog's name and 'says woof'.
  3. Final Answer:

    "Buddy says woof" -> Option C
  4. Quick Check:

    Method returns correct string with name [OK]
Hint: Look for method return values matching console.log output [OK]
Common Mistakes:
  • Assuming missing method error when method exists
  • Confusing property values with method output
  • Ignoring string template usage
4. Identify the error in this code:
interface Shape {
  area(): number;
}

class Circle implements Shape {
  radius: number;
  constructor(radius: number) {
    this.radius = radius;
  }
  area(): string {
    return (Math.PI * this.radius * this.radius).toFixed(2);
  }
}
medium
A. Method area() returns string instead of number.
B. Missing constructor in Circle class.
C. radius property is not declared.
D. Circle should extend Shape, not implement.

Solution

  1. Step 1: Check interface method signature

    Interface Shape requires area() to return a number.
  2. Step 2: Compare with class method return type

    Circle's area() returns a string because toFixed() returns string.
  3. Final Answer:

    Method area() returns string instead of number. -> Option A
  4. Quick Check:

    Return type must match interface [OK]
Hint: Match method return types exactly with interface [OK]
Common Mistakes:
  • Returning string when interface expects number
  • Forgetting to declare properties
  • Using extends instead of implements for interfaces
5. You have two interfaces:
interface Printer {
  print(): void;
}
interface Scanner {
  scan(): void;
}

How can you create a class AllInOneMachine that implements both interfaces correctly?
hard
A. interface AllInOneMachine implements Printer, Scanner {}
B. class AllInOneMachine implements Printer { print() { console.log('Printing'); } scan() { console.log('Scanning'); } }
C. class AllInOneMachine extends Printer, Scanner { print() { console.log('Printing'); } scan() { console.log('Scanning'); } }
D. class AllInOneMachine implements Printer, Scanner { print() { console.log('Printing'); } scan() { console.log('Scanning'); } }

Solution

  1. Step 1: Understand multiple interface implementation

    TypeScript allows a class to implement multiple interfaces separated by commas.
  2. Step 2: Check class methods match all interfaces

    Class must have both print() and scan() methods.
  3. Final Answer:

    class AllInOneMachine implements Printer, Scanner { print() { console.log('Printing'); } scan() { console.log('Scanning'); } } -> Option D
  4. Quick Check:

    Multiple interfaces implemented with comma [OK]
Hint: Use comma to implement multiple interfaces in one class [OK]
Common Mistakes:
  • Using extends instead of implements for interfaces
  • Implementing only one interface but adding all methods
  • Trying to implement interfaces in interface declaration
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard