Discover how to upgrade your classes without rewriting them and save hours of work!
Why Merging classes with interfaces in Typescript? - Purpose & Use Cases
Imagine you have a class that defines some behavior, and separately you want to add extra properties or methods to it without changing the original class code. Doing this manually means rewriting or duplicating code, which is confusing and error-prone.
Manually copying or extending classes to add new features can lead to mistakes, duplicated code, and harder maintenance. It's like trying to add new features to a car by building a whole new car from scratch every time.
Merging classes with interfaces lets you extend or add new properties to a class type without changing the original class code. It's like attaching new parts to your car easily without rebuilding it, keeping your code clean and flexible.
class Car { drive() { console.log('Driving'); } } // To add new property, create a new class or duplicate code
class Car { drive() { console.log('Driving'); } } interface Car { color: string; } // Now Car instances have color property without changing class
This concept enables you to enhance existing classes with new properties or methods seamlessly, making your code more adaptable and easier to maintain.
Suppose you have a User class but later want to add an address property. Instead of rewriting the class, you merge an interface with the User class to add the address, keeping your original code untouched.
Merging classes with interfaces avoids code duplication.
It allows adding new features without changing original classes.
It keeps code clean, flexible, and easier to maintain.
Practice
What happens when you declare an interface with the same name as a class in TypeScript?
For example:class Car { drive() {} }
interface Car { color: string; }
Solution
Step 1: Understand interface and class merging
In TypeScript, if an interface has the same name as a class, their types merge. This means the class type now includes members from both.Step 2: Apply to example
The interface adds a 'color' property to the class type, so instances of Car are expected to have 'drive()' and 'color'.Final Answer:
The interface merges with the class, adding the 'color' property to the class type. -> Option BQuick Check:
Same name interface + class = merged type [OK]
- Thinking interface replaces class
- Expecting a syntax error
- Assuming class ignores interface
Which of the following is the correct syntax to merge an interface with a class named Person in TypeScript?
Solution
Step 1: Recall interface declaration syntax
Interfaces are declared with the keyword 'interface' followed by the name and curly braces containing members.Step 2: Check each option
interface Person { age: number; } uses correct syntax: 'interface Person { age: number; }'. Options A, C, and D use invalid syntax like parentheses, brackets, or equals sign.Final Answer:
interface Person { age: number; } -> Option AQuick Check:
Correct interface syntax = interface Person { age: number; } [OK]
- Using parentheses after interface name
- Using brackets instead of braces
- Assigning interface with equals sign
Given the following code, what is the output?
class Animal {
speak() { return "Roar"; }
}
interface Animal {
age: number;
}
const a: Animal = { age: 5, speak() { return "Roar"; } };
console.log(a.age, a.speak());Solution
Step 1: Understand merging and object literal
The interface adds 'age' to Animal type. The object 'a' has both 'age' and 'speak' method matching Animal type.Step 2: Check console.log output
Logging 'a.age' prints 5, and 'a.speak()' returns "Roar". So output is '5 Roar'.Final Answer:
5 Roar -> Option DQuick Check:
Object has both properties, prints values [OK]
- Expecting undefined for age
- Confusing method call with property
- Thinking runtime error occurs
Identify the error in this code that merges a class and interface named Book:
class Book {
title: string;
constructor(title: string) {
this.title = title;
}
}
interface Book {
author: string;
}
const b = new Book("1984");
console.log(b.author);Solution
Step 1: Check merging requirements
The interface adds 'author' property to Book type, but the class does not implement it or assign it.Step 2: Analyze runtime behavior
Creating 'b' with new Book("1984") sets 'title' but 'author' is undefined. Accessing 'b.author' prints undefined, which may cause issues if expected to exist.Final Answer:
Property 'author' is missing in class implementation causing runtime error. -> Option CQuick Check:
Interface adds property, class must implement it [OK]
- Thinking names must differ
- Ignoring missing property implementation
- Assuming no error occurs
You want to extend a class Employee by merging an interface with the same name to add a new method getSalary(). How should you correctly implement this so that getSalary() is usable on Employee instances?
class Employee {
name: string;
constructor(name: string) {
this.name = name;
}
}
interface Employee {
getSalary(): number;
}
// What is the correct way to implement getSalary?Solution
Step 1: Understand interface merging with class
Merging adds type info but does not add implementation. The class must implement the method or it will cause errors.Step 2: Implement method correctly
Since the class does not have getSalary(), adding it to Employee.prototype after declaration provides the implementation and satisfies the interface.Final Answer:
Add getSalary() method to Employee.prototype after class declaration. -> Option AQuick Check:
Interface adds type; method must be implemented in class or prototype [OK]
- Adding method only in interface without implementation
- Trying to add method outside prototype
- Assuming interface adds implementation automatically
Ready to prove it?
Pass the test and this pattern moves unknown
