Objects, Interfaces and Type Aliases · Lesson 5 of 17
TypeScript Interfaces and Object Types
Most data in real apps is objects: users, orders, API responses, component props. An interface describes an object's shape – which properties it has and their types – so TypeScript can check every place the object is created or used. Interfaces are the backbone of typed React props, Angular models and Node APIs.
In this lesson
- Declaring interfaces and using them
- Optional and readonly properties
- Methods and index signatures
- Extending interfaces
A first interface
interface User {
id: number;
name: string;
email: string;
isAdmin: boolean;
}
function greet(user: User): string {
return `Hi ${user.name}${user.isAdmin ? " (admin)" : ""}`;
}
const asha: User = { id: 1, name: "Asha", email: "asha@example.com", isAdmin: true };
console.log(greet(asha));
console.log(greet({ id: 2, name: "Ravi", email: "ravi@example.com", isAdmin: false }));
Hi Asha (admin) Hi Ravi
TypeScript checks objects structurally: any object with the right properties is a User, whether or not it was declared as one. That's "duck typing" made safe.
Missing, extra and misspelt properties
interface Product {
name: string;
price: number;
}
const a: Product = { name: "Mouse" };
const b: Product = { name: "Pen", price: 20, colour: "blue" };
const c: Product = { name: "Book", prise: 450 };
console.log(a, b, c);
main.ts(5,7): error TS2741: Property 'price' is missing in type '{ name: string; }' but required in type 'Product'.
main.ts(6,46): error TS2353: Object literal may only specify known properties, and 'colour' does not exist in type 'Product'.
main.ts(7,36): error TS2561: Object literal may only specify known properties, but 'prise' does not exist in type 'Product'. Did you mean to write 'price'?Object literals get an "excess property check": an unknown property is almost always a typo, so TypeScript rejects it.
Optional and readonly properties
interface Order {
readonly id: number; // can't be changed after creation
items: string[];
coupon?: string; // optional: string | undefined
deliveredAt?: Date;
}
function summary(order: Order): string {
const discount = order.coupon ? ` with coupon ${order.coupon}` : "";
return `Order #${order.id}: ${order.items.length} items${discount}`;
}
const o1: Order = { id: 101, items: ["pen", "book"] };
const o2: Order = { id: 102, items: ["bag"], coupon: "SAVE10" };
o2.items.push("lamp"); // allowed: the array itself isn't readonly
// o2.id = 999; // error: Cannot assign to 'id' because it is a read-only property
console.log(summary(o1));
console.log(summary(o2));
console.log(o1.coupon?.toUpperCase() ?? "no coupon");
Order #101: 2 items Order #102: 2 items with coupon SAVE10 no coupon
Optional means "might be undefined"
Under strict mode you can't call methods on an optional property without checking it first. Use if, optional chaining (?.) or a default (??). And readonly is shallow: a readonly array property can't be reassigned, but its contents can change unless its type is readonly string[].
Methods and index signatures
interface Cart {
items: Record<string, number>; // name → quantity
add(name: string, qty?: number): void; // method signature
total(prices: { [product: string]: number }): number; // index signature
}
const cart: Cart = {
items: {},
add(name, qty = 1) { // parameter types come from the interface
this.items[name] = (this.items[name] ?? 0) + qty;
},
total(prices) {
let sum = 0;
for (const [name, qty] of Object.entries(this.items)) sum += (prices[name] ?? 0) * qty;
return sum;
},
};
cart.add("pen", 3);
cart.add("book");
console.log(cart.items, cart.total({ pen: 20, book: 450 }));
{ pen: 3, book: 1 } 510An index signature { [key: string]: number } (or the shorthand Record<string, number>) describes dictionary-like objects whose keys aren't known in advance.
Extending interfaces
interface Person {
name: string;
email: string;
}
interface Employee extends Person {
employeeId: number;
department: string;
}
interface Manager extends Employee {
reports: Employee[];
}
const dev: Employee = { name: "Sana", email: "sana@example.com", employeeId: 3, department: "Engineering" };
const lead: Manager = {
name: "Rohit", email: "rohit@example.com", employeeId: 2, department: "Engineering", reports: [dev],
};
function contact(p: Person): string { return `${p.name} <${p.email}>`; } // accepts any Person
console.log(contact(dev), "|", contact(lead), "|", lead.reports.length);
Sana <sana@example.com> | Rohit <rohit@example.com> | 1
Practice
Try it yourself
Define an interface
Coursewith a readonly slug, title, optional price and a list of lesson titles, and writedescribe(c: Course)that prints "Free" when there's no price.Show solution
interface Course { readonly slug: string; title: string; price?: number; lessons: readonly string[]; } function describe(c: Course): string { const cost = c.price === undefined ? "Free" : `Rs ${c.price}`; const n = c.lessons.length; return `${c.title} (${n} lesson${n === 1 ? "" : "s"}) – ${cost}`; } console.log(describe({ slug: "ts", title: "TypeScript", lessons: ["Intro", "Types"] })); console.log(describe({ slug: "cpp", title: "C++", price: 499, lessons: ["STL"] }));TypeScript (2 lessons) – Free C++ (1 lesson) – Rs 499
Quick check
What does email?: string mean?
The property may be missing; its type is string | undefined.
Is an object with extra properties a valid User?
Structurally yes when passed as a variable; but an object literal with unknown properties is rejected by the excess property check.
How do you type a dictionary with unknown string keys?
An index signature { [key: string]: T } or Record<string, T>.
Summary
- Interfaces describe object shapes; TypeScript checks them structurally.
- ? marks optional properties (handle undefined); readonly prevents reassignment.
- Index signatures/Record type dictionaries; extends builds bigger interfaces from smaller ones.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.