Understanding Interface in TypeScript

An interface in TypeScript is a powerful way to define the structure of an object. It acts like a contract within your code or a blueprint for an object. When you create an interface, you specify the properties and their types that an object must have. This helps TypeScript’s compiler to catch errors and ensure that objects always meet the required shape.

Why Use Interface?

  1. Type Checking: Interface help the compiler check if an object meets the criteria set in the interface. This reduces runtime errors and bugs.
  2. Readability: They make your code more descriptive. When you see an interface, it’s easy to understand what properties and methods you can expect on a given object.
  3. Reusability: You can reuse interface across your application, ensuring consistency in how certain types are defined and enforced.

Basic Usage

interface Person {
  name: string;
  age: number;
}

// Using the interface in a function
function greet(person: Person): string {
  return `Hello, my name is ${person.name} and I am ${person.age} years old.`;
}

// An object that implements the Person interface
const user: Person = {
  name: "Alice",
  age: 25,
};

console.log(greet(user));
// Output: Hello, my name is Alice and I am 25 years old.

Optional Properties

You can mark certain properties as optional by adding a question mark (?). This tells TypeScript that the property may or may not exist.

interface Vehicle {
  make: string;
  model: string;
  year?: number; // Optional
}

const car: Vehicle = {
  make: "Toyota",
  model: "Corolla",
};

const bike: Vehicle = {
  make: "Yamaha",
  model: "MT-15",
  year: 2021,
};

Here, year is not required. Both car and bike objects are valid against the Vehicle interface.

interface Book {
  readonly title: string;
  author: string;
}

Readonly Properties

const myBook: Book = { title: "1984", author: "George Orwell" };
// myBook.title = "Animal Farm"; 
// Error: Cannot assign to 'title' because it is a read-only property.

Here once myBook is created, the title property cannot be modified.

lets talk about method signatures

Interface also define methods

interface Greeter {
  greet(): void;
}

interface PersonWithGreeter extends Greeter {
  name: string;
  age: number;
}

const userWithGreeter: PersonWithGreeter = {
  name: "Bob",
  age: 30,
  greet() {
    console.log(`Hello, I am ${this.name}`);
  },
}; 

userWithGreeter.greet();
// Output: Hello, I am Bob

Interface in TypeScript provide a robust way to define and enforce the shape of objects, improving code clarity and preventing a large class of runtime errors. They are a foundational feature of TypeScript’s type system, helping you write more reliable and maintainable code.

Enjoy coding !!!