Junior — Middle
In what situations is it recommended to use interfaces in TypeScript?
sobes.tech AI
Answer from AI
Interfaces in TypeScript are recommended for use in the following situations:
- Defining contracts for objects to ensure that objects have a specific structure.
- Describing data formats, for example, for function parameters or return values.
- Ensuring type safety when working with classes and objects.
- Creating abstractions that can be implemented by different classes.
- Improving code readability and maintainability through explicit type descriptions.
Example:
interface User {
id: number;
name: string;
email?: string; // optional field
}
function greet(user: User) {
console.log(`Hello, ${user.name}`);
}
const user = { id: 1, name: "Ivan" };
greet(user);
Here, the User interface defines the structure of a user object, which helps prevent errors and enhances autocomplete in the editor.