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.
Interface declaration syntax in 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.
name and age.interface Person {
name: string;
age: number;
}interface Calculator {
add(a: number, b: number): number;
subtract(a: number, b: number): number;
}brand property and a start method that returns nothing.interface Car {
brand: string;
start(): void;
}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.
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();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.
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.