TypeScript Interfaces
An interface describes the shape of an object: which properties it must have and what type each property is. Interfaces are one of the most common ways to define object types in TypeScript.
When an object is checked against an interface, TypeScript verifies that all required properties are present with the correct types. If a property is missing or has the wrong type, TypeScript reports an error.
interface User {
name: string;
age: number;
}Defining an interface
You use the `interface` keyword followed by a name and a block listing property names and types, such as `interface User { name: string; age: number; }`.
Using an interface
Once defined, you can annotate variables, function parameters, or return types with the interface name to enforce that shape wherever it's used.
interface User {
name: string;
age: number;
}
const user: User = { name: "Lee", age: 22 };
console.log(`${user.name}, ${user.age}`);Lee, 22The user object must match the User interface exactly, including both required properties.
interface Product {
title: string;
price: number;
}
function printProduct(p: Product) {
console.log(`${p.title}: $${p.price}`);
}
printProduct({ title: "Book", price: 12 });Book: $12The function parameter is typed using the Product interface to enforce its shape.
Key points
- Interfaces describe the required shape of an object.
- They are defined with the `interface` keyword.
- TypeScript checks that objects match all required properties and types.
- Interfaces are commonly used to type function parameters and return values.
