Introduction
Interfaces help us describe the shape of data clearly. They make sure different parts of a program agree on what data looks like.
Interfaces help us describe the shape of data clearly. They make sure different parts of a program agree on what data looks like.
interface InterfaceName {
propertyName: type;
methodName(param: type): returnType;
}interface Person {
name: string;
age: number;
}interface Logger {
log(message: string): void;
}interface Product {
id: number;
name: string;
price?: number; // optional property
}This program uses an interface to make sure the car object has the right properties before printing.
interface Car {
make: string;
model: string;
year: number;
}
function printCar(car: Car) {
console.log(`Car: ${car.make} ${car.model} (${car.year})`);
}
const myCar: Car = { make: "Toyota", model: "Corolla", year: 2020 };
printCar(myCar);Interfaces help catch errors before running the code by checking types.
They improve code readability by clearly showing what data is expected.
Interfaces can be extended to build more complex types from simple ones.
Interfaces describe the shape of data to keep code consistent.
They help catch mistakes early by checking types during development.
Using interfaces makes code easier to read and maintain.
interfaces in TypeScript?interface followed by the name and curly braces.interface correctly; others use class, type alias, or function.interface User { id: number; name: string; }
const user: User = { id: 1, name: "Alice" };
console.log(user.name);User requires id and name. The object matches this shape.user.name, which is "Alice" as assigned.interface Product { id: number; name: string; }
const product: Product = { id: 10 };id and name properties.id, missing name, causing a type error.title string property and an optional description string property. Which interface best fits this need?title as required string, description optional string.title required, description optional. Others either make title optional or wrong type.Pass the test and this pattern moves unknown