Real programs work with structured data — a student, an order, a product. An interface (or a type alias) describes the shape of an object: which properties it has and their types. Mark properties ? when optional and readonly when they must not change.
Arrays of objects are processed with array methods instead of manual loops: filter keeps items that match a test, map transforms each item, find returns the first match, and reduce combines all items into one value (such as a total).
These methods never change the original array — they return new values, which makes code easier to reason about.
interface Student {
readonly id: number;
name: string;
form: number;
score: number;
email?: string;
}
const students: Student[] = [
{ id: 1, name: "Amina", form: 4, score: 88 },
{ id: 2, name: "Baraka", form: 3, score: 54, email: "baraka@example.com" },
{ id: 3, name: "Neema", form: 4, score: 71 },
];
const formFour = students.filter((s) => s.form === 4);
const names = formFour.map((s) => s.name.toUpperCase());
const top = students.find((s) => s.score >= 85);
const total = students.reduce((sum, s) => sum + s.score, 0);
const average = total / students.length;
console.log(names); // [ 'AMINA', 'NEEMA' ]
console.log(top?.name ?? "No top student");
console.log("Average:", average.toFixed(1));
type Summary = { count: number; average: number };
const summary: Summary = { count: students.length, average };
console.log(summary);Key points
- Describe data shapes with
interfaceortypebefore writing logic. filter,map,find,reducereplace most manual loops.?.safely reads from a value that may be undefined;??supplies a fallback.
Exercise
Define a Product interface (name, price, quantity, optional category). From an array of products compute: the names of products under 5,000 TSh, the total stock value (price × quantity), and the most expensive product.
Show solution
Try the exercise yourself first — then compare your approach with this one.
Describe the data with an interface first. Then filter + map gives the cheap product names, reduce adds up price × quantity, and a reduce that keeps the larger item finds the most expensive product.
interface Product {
name: string;
price: number;
quantity: number;
category?: string;
}
const products: Product[] = [
{ name: "Exercise book", price: 1500, quantity: 200, category: "Stationery" },
{ name: "Scientific calculator", price: 35000, quantity: 12 },
{ name: "Geometry set", price: 4500, quantity: 40, category: "Stationery" },
{ name: "School bag", price: 25000, quantity: 15, category: "Bags" },
];
const cheap = products.filter((p) => p.price < 5000).map((p) => p.name);
const stockValue = products.reduce((sum, p) => sum + p.price * p.quantity, 0);
const mostExpensive = products.reduce((best, p) => (p.price > best.price ? p : best));
console.log(cheap); // [ 'Exercise book', 'Geometry set' ]
console.log(stockValue); // 1275000
console.log(mostExpensive.name); // Scientific calculator