0
0
Typescriptprogramming~5 mins

Interface declaration syntax in Typescript

Choose your learning style9 modes available
Introduction

An interface in TypeScript helps you describe the shape of an object. It tells what properties and methods an object should have, like a blueprint.

When you want to define the structure of an object clearly before using it.
When you want to make sure different parts of your code use objects with the same properties.
When you want to describe the shape of data coming from an API.
When you want to create reusable contracts for classes or objects.
When you want to catch mistakes early by checking object shapes during coding.
Syntax
Typescript
interface InterfaceName {
  propertyName: propertyType;
  methodName(param: paramType): returnType;
}

The interface keyword starts the declaration.

Properties and methods inside the interface do not have implementations, only their types.

Examples
This interface describes a person with a name and age.
Typescript
interface Person {
  name: string;
  age: number;
}
This interface describes a calculator with two methods that take numbers and return a number.
Typescript
interface Calculator {
  add(a: number, b: number): number;
  subtract(a: number, b: number): number;
}
This interface describes a car with a brand property and a start method that returns nothing.
Typescript
interface Car {
  brand: string;
  start(): void;
}
Sample Program

This program defines a User interface with two properties and one method. Then it creates an object user that follows this interface and calls the login method.

Typescript
interface User {
  username: string;
  email: string;
  login(): void;
}

const user: User = {
  username: "alice123",
  email: "alice@example.com",
  login() {
    console.log(`${this.username} logged in`);
  }
};

user.login();
OutputSuccess
Important Notes

Interfaces only exist during development and are removed when the code runs.

You can extend interfaces to build bigger interfaces from smaller ones.

Interfaces help catch errors early by checking object shapes before running the code.

Summary

Interfaces describe the shape of objects with properties and methods.

They help keep your code organized and error-free by defining clear contracts.

Use interface keyword followed by the name and the list of properties/methods.