Junior — Middle
What distinguishes interfaces from classes in TypeScript, and in which situations is each used?
sobes.tech AI
Answer from AI
In TypeScript, interfaces and classes have different purposes and features:
- Interfaces describe the structure of data — what properties and methods an object should have. They do not contain implementation, serving for typing and contracts.
- Classes are templates for creating objects with method implementations and state (properties). Classes can contain constructors, methods with bodies, and access modifiers.
When to use:
- Interfaces are used to describe data formats, especially when only the structure matters, such as for function parameters or objects.
- Classes are used when logic implementation, creating instances with behavior, and inheritance are needed.
Example of an interface:
interface IUser {
id: number;
name: string;
}
Example of a class:
class User implements IUser {
constructor(public id: number, public name: string) {}
greet() {
console.log(`Hello, ${this.name}`);
}
}
Thus, interfaces are contracts, and classes are concrete implementations with behavior.