Interfaces in TypeScript are used to define the shape (structure) of an object. They specify the properties and methods that an object should have, without providing implementation.
🔹 Key Points:
- Define type contracts for objects, functions, or classes.
- Ensure type safety and better code autocompletion.
- Interfaces do not exist in JavaScript — they are a TypeScript-only feature for static type checking.
✅ Basic Example:
interface User {
name: string;
age: number;
isAdmin?: boolean; // optional property
}
const user1: User = {
name: "Teekam",
age: 25,
};
✅ Interface for Functions:
interface Greet {
(name: string): string;
}
const greetUser: Greet = (name) => {
return `Hello, ${name}`;
};
✅ Interface with Classes:
interface Person {
name: string;
speak(): void;
}
class Student implements Person {
name: string;
constructor(name: string) {
this.name = name;
}
speak() {
console.log(`Hi, I'm ${this.name}`);
}
}
✅ Extending Interfaces:
interface Employee {
id: number;
}
interface Manager extends Employee {
teamSize: number;
}
📝 In Summary:
Interfaces in TypeScript define object blueprints, help with code organization, and improve type safety in larger applications.