Introduction to Interfaces


Introduction to Interfaces#
Interfaces in TypeScript define contracts for objects, specifying the expected structure and behavior. They help ensure your code is consistent, maintainable, and type-safe.
What Are Interfaces?
An interface describes the shape of an object: what properties it has, their types, and whether they are optional or readonly.
interface Person {
name: string;
age: number;
}This interface requires a Person object to have a name string and an age number.
Defining Interfaces
You define interfaces using the interface keyword:
interface Car {
make: string;
model: string;
year: number;
}Interfaces can be used to type variables, function parameters, and return types:
function printCar(car: Car): void {
console.log(`${car.make} ${car.model} (${car.year})`);
}Optional Properties
Properties can be marked optional with ?:
interface Person {
name: string;
age?: number; // optional
}
const alice: Person = { name: "Alice" };
const bob: Person = { name: "Bob", age: 30 };Optional properties allow flexibility when some data may not be present.
Readonly Modifiers
Use readonly to prevent properties from being changed after initialization:
interface Point {
readonly x: number;
readonly y: number;
}
const p: Point = { x: 10, y: 20 };
// p.x = 5; // Error: Cannot assign to 'x' because it is a read-only property.Readonly properties help enforce immutability.
Using Interfaces
Interfaces can be implemented by classes or used as types for objects:
class Employee implements Person {
constructor(
public name: string,
public age: number
) {}
}
const emp = new Employee("John", 40);
console.log(emp.name); // JohnBest Practices
- Use interfaces to define clear contracts for objects and classes.
- Prefer interfaces over inline object types for reusable shapes.
- Use optional properties to handle partial data gracefully.
- Use readonly modifiers to protect immutable data.
- Document interfaces to clarify expected usage.
Tip: Interfaces can be extended and merged, making them powerful for complex type definitions (covered in advanced patterns).
Common Mistakes
- Forgetting to mark optional properties, causing unnecessary errors.
- Modifying readonly properties, leading to compile-time errors.
- Using interfaces for primitive types or unions (use type aliases instead).
- Overusing interfaces for one-off object shapes instead of inline types.
Next Steps
Next, explore advanced interface patterns including extension, hybrid types, and index signatures to model complex data structures.