What is the difference between Classes and Interfaces in Typescript?
What is the difference between Classes and Interfaces in Typescript?
In TypeScript, both classes and interfaces are foundational concepts used to structure and type-check code, but they serve different purposes and have distinct characteristics.
A class in TypeScript is a blueprint for creating objects with specific properties and methods. It encapsulates data for the object and can include functionalities. Classes are used to instantiate new objects using the new
keyword, allowing for the creation of multiple instances, each with their own set of data and behaviors.
public
, private
, and protected
which control the accessibility of the class members.Example of a TypeScript class:
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
move(distance: number) {
console.log(`${this.name} moved ${distance}m.`);
}
}
An interface in TypeScript is a structure that defines the shape of an object but does not implement any real functionality. Interfaces are used to type-check whether an object fits a certain structure. They are purely a compile-time construct and do not generate any JavaScript code.
junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào