In TypeScript, an interface is a way to define a contract for the structure of an object. It specifies the properties and their types that an object must have. Interfaces are especially useful when working with React and TypeScript, as they help define the shape of props, states, and other data structures.
- Defines Object Shape: Specifies the structure of an object.
- Type Checking: Ensures that the object adheres to the defined structure.
- Extensibility: Can extend other interfaces.
- Optional Properties: Use
?to mark properties as optional. - Read-Only Properties: Use
readonlyto make properties immutable. - Functions: Can define function signatures.
interface InterfaceName {
property1: Type;
property2?: Type; // Optional property
readonly property3: Type; // Read-only property
method1(param: Type): ReturnType; // Function signature
}interface User {
id: number;
name: string;
email?: string; // Optional property
}
const user1: User = {
id: 1,
name: "John Doe",
email: "john.doe@example.com",
};
const user2: User = {
id: 2,
name: "Jane Doe", // Valid even without email because it's optional
};interface Product {
id: number;
name: string;
price: number;
}
function displayProduct(product: Product): string {
return `Product: ${product.name}, Price: $${product.price}`;
}
const product: Product = { id: 101, name: "Laptop", price: 999 };
console.log(displayProduct(product));You can create a new interface that extends an existing one.
interface Person {
name: string;
age: number;
}
interface Employee extends Person {
employeeId: number;
department: string;
}
const employee: Employee = {
name: "Alice",
age: 30,
employeeId: 12345,
department: "IT",
};In React, interfaces are commonly used to type props:
import React from "react";
interface ButtonProps {
label: string;
onClick: () => void; // Function type
}
const Button: React.FC<ButtonProps> = ({ label, onClick }) => {
return <button onClick={onClick}>{label}</button>;
};
export default Button;- Type Safety: Prevents runtime errors by catching issues during development.
- Code Readability: Makes the code self-documenting and easier to understand.
- Extensibility: Interfaces can be extended to add new features without breaking existing code.