Overview
Interfaces in TypeScript are powerful constructs that allow you to define the shape of an object, ensuring that objects meet a certain contract. They are used to type-check whether a certain object fits a particular structure. Interfaces are crucial in TypeScript for creating cohesive, well-structured code, especially when working with complex systems where strict typing helps to avoid errors and improve maintainability.
Key Concepts
- Type Checking: Interfaces in TypeScript are used primarily for type checking, ensuring objects adhere to a specific structure.
- Extensibility: Interfaces can be extended, allowing for more flexible and reusable code structures.
- Integration with Classes: Interfaces can be implemented by classes, which is a way of enforcing that a class meets a particular contract.
Common Interview Questions
Basic Level
- What is an interface in TypeScript and why is it used?
- Can you provide a simple example of an interface in TypeScript?
Intermediate Level
- How do interfaces compare to types in TypeScript?
Advanced Level
- Can interfaces in TypeScript extend multiple interfaces? Provide an example.
Detailed Answers
1. What is an interface in TypeScript and why is it used?
Answer: An interface in TypeScript is a syntactical contract that an entity should conform to. It defines the shape of an object, including the properties and types those properties should have, without providing implementation details. Interfaces are used for type-checking purposes, to ensure that objects have the expected structure. They are particularly useful in large codebases for maintaining consistency and predictability in the structure of objects.
Key Points:
- Interfaces define properties, methods, and events, which are then implemented by classes.
- They help in enforcing structure and consistency across objects.
- Interfaces are a design-time construct and do not translate into JavaScript after compilation.
Example:
interface User {
name: string;
age: number;
}
function registerUser(user: User) {
console.log(`Registering user ${user.name} aged ${user.age}`);
}
// Correct usage
registerUser({name: "Alice", age: 30});
// Incorrect usage will result in a compile-time error
// registerUser({name: "Bob"}); // Error: Property 'age' is missing
2. Can you provide a simple example of an interface in TypeScript?
Answer: An interface in TypeScript can be used to define the structure of an object, including its properties and the types of those properties. Here's a simple example:
Key Points:
- Interfaces are used to define custom types.
- They can include optional properties.
- Interfaces ensure type safety by checking the shape of the objects.
Example:
interface Vehicle {
make: string;
model: string;
year: number;
}
function printVehicleInfo(vehicle: Vehicle) {
console.log(`Vehicle Info: ${vehicle.make} ${vehicle.model} (${vehicle.year})`);
}
const myCar: Vehicle = {
make: "Toyota",
model: "Camry",
year: 2020
};
printVehicleInfo(myCar);
3. How do interfaces compare to types in TypeScript?
Answer: Both interfaces and types in TypeScript are used for defining the shape of objects, but they have some differences in how they are used and what features they support.
Key Points:
- Extensibility: Interfaces are extendable, allowing for the creation of new interfaces that extend the properties of existing ones. Types can use intersection types for a similar purpose but are not extendable in the same way interfaces are.
- Declaration Merging: Interfaces support declaration merging, where multiple declarations of the same interface in a codebase automatically merge to form a single interface. Types do not support this.
- Use Cases: Types are more versatile and can represent not just the shape of objects but also unions, primitives, and tuples.
Example:
interface Person {
name: string;
}
interface Employee extends Person {
employeeId: number;
}
// Type example
type Animal = {
species: string;
};
// Creating a union type
type Pet = Animal & { name: string; };
// Interface declaration merging is not possible with types
4. Can interfaces in TypeScript extend multiple interfaces? Provide an example.
Answer: Yes, interfaces in TypeScript can extend multiple interfaces, allowing you to combine several interfaces into one. This is useful for composing complex types from simpler ones.
Key Points:
- Multiple inheritance: Interfaces can inherit from multiple interfaces, enabling more complex type definitions.
- Code reusability: This feature enhances code reusability and modularity.
- Combining interfaces: When an interface extends multiple interfaces, the resulting interface inherits properties from all the parent interfaces.
Example:
interface NamedEntity {
name: string;
}
interface Timestamped {
createdAt: Date;
updatedAt: Date;
}
// Extending multiple interfaces
interface User extends NamedEntity, Timestamped {
email: string;
}
const newUser: User = {
name: "Jane Doe",
createdAt: new Date(),
updatedAt: new Date(),
email: "jane.doe@example.com"
};
console.log(newUser);
This example demonstrates how interfaces can be used to compose more complex types by extending multiple simpler interfaces, ensuring structured and maintainable code.