An interface is a way to define a contract that specifies the structure of an object. It defines the properties and methods that an object should have. Interfaces provide a mechanism for type checking and ensure that objects adhere to a certain shape.
interface Person {
firstName: string;
lastName: string;
age: number;
}
const person: Person = {
firstName: "John",
lastName: "Doe",
age: 30
};
In this example, the Person
interface defines a contract that requires objects of type Person
to have firstName
, lastName
, and age
properties. The person
object adheres to this contract, so TypeScript will perform type checking to ensure that only objects with the required properties can be assigned to variables of type Person
.
Interfaces can be used for various purposes:
- Type Checking: Interfaces help catch errors during development by ensuring that objects meet specific structural requirements.
- Code Organization: Interfaces can help document the expected structure of objects, making the codebase more understandable and maintainable.
- Function Signatures: Interfaces can define the shape of function signatures, specifying the parameter types and return type.
- Extending Interfaces: Interfaces can extend other interfaces, inheriting their properties and methods.
interface Employee extends Person {
employeeId: string;
position: string;
}
const employee: Employee = {
firstName: "Jane",
lastName: "Smith",
age: 28,
employeeId: "12345",
position: "Manager"
};
Optional Properties: You can mark properties as optional using the ?
symbol.
interface Configuration {
readonly apiKey: string;
baseUrl: string;
}
const config: Configuration = {
apiKey: "abc123",
baseUrl: "https://example.com"
};
// Cannot modify apiKey after initialization
config.apiKey = "newApiKey"; // Error
NOTE:- The key distinction is that a type cannot be re-opened to add new properties vs an interface which is always extendable.