Interfaces and Object Types
Describe object shapes with interface and type, extend interfaces, use optional properties with ?, and readonly for immutability.
interface vs type
Both interface and type describe object shapes. The key difference: interfaces can be merged (declaration merging) and are generally preferred for defining public API shapes. type aliases are more flexible for complex types.
// interface:
interface User {
id: number;
name: string;
}
// type alias (equivalent for objects):
type User = {
id: number;
name: string;
};Defining an Interface
Use interface to define the shape of an object. All properties are required by default. Separate properties with semicolons.
interface Product {
id: number;
name: string;
price: number;
description: string;
inStock: boolean;
category: string;
}