Objects and Interfaces
An interface describes the shape an object must have — which properties it needs, and what type each one is. Once you write one, TypeScript checks every object you claim matches it.
interface Person {
name: string;
age: number;
}
let alice: Person = { name: "Alice", age: 30 };
console.log(alice);
console.log(alice.name);{ name: 'Alice', age: 30 }
AliceOptional properties and readonly
A ? after a property name makes it optional — an object can leave it out entirely. readonly marks a property that can be set once (usually when the object is created) but never reassigned after that.
interface Product {
readonly id: number;
name: string;
discount?: number;
}
let item: Product = { id: 1, name: "Keyboard" };
console.log(item);
item.name = "Mechanical Keyboard";
console.log(item);{ id: 1, name: 'Keyboard' }
{ id: 1, name: 'Mechanical Keyboard' }item.id = 2 would be flagged immediately — readonly is enforced at compile time, the same way every other type rule is.
Next: type aliases and union types — naming a type, and describing a value that could be more than one type.
Practice exercise
Define an interface Book with title: string and pages: number. Create a book with title "Dune" and pages 412, then print book.title and book.pages using console.log(book.title, book.pages).