Member-only story

For more questions and answers visit our website at Frontend Interview Questions
What is an Interface in TypeScript?
An interface is a syntactical contract that defines the structure of an object. It specifies what properties and methods an object should have without providing the implementation. Interfaces are ideal for defining object shapes, especially when you want to enforce consistency across different parts of your code or across different modules.
Example of an Interface
Here’s a simple example of an interface in TypeScript:
interface User {
id: number;
name: string;
email: string;
}
const user1: User = {
id: 1,
name: "Alice",
email: "alice@example.com"
};
In this example, the User
interface defines three properties: id
, name
, and email
. The user1
object adheres to this structure, ensuring that it has all the required properties.
What is a Class in TypeScript?
A class in TypeScript is a blueprint for creating objects. It encapsulates data (properties) and behavior (methods) related to that data. Classes can also implement interfaces, allowing you to define both structure and behavior.