Junior — Middle
Can you explain what interfaces mean in TypeScript?
sobes.tech AI
Answer from AI
In TypeScript, interfaces are used to describe the structure of objects, meaning they define what properties and methods an object should have. An interface sets a contract that an object must adhere to, but it does not contain an implementation.
Example of an interface:
interface User {
id: number;
name: string;
isActive: boolean;
greet(): void;
}
const user: User = {
id: 1,
name: "Ivan",
isActive: true,
greet() {
console.log(`Hello, ${this.name}`);
}
};
user.greet(); // Outputs: Hello, Ivan
Interfaces help ensure type safety and ease of working with objects, as well as serve to describe contracts in functions, classes, and other structures.