Expert · TypeScript basics · topic 52 of 64 · 35 min
Typing functions and objects
Explanation
Parameter and return types
function gst(price: number, rate: number): number {
return (price * rate) / 100;
}
gst(500, 18); // 90
gst(500); // Error: Expected 2 arguments, but got 1.
gst("500", 18); // Error: Argument of type 'string' is not assignable to parameter of type 'number'.Parameters need types, because TypeScript cannot guess what callers will pass. The return type can usually be inferred, but writing it is a good habit: it documents the function and catches a wrong return early.
Optional and default parameters, and void
function greet(name: string, title?: string): string {
return title ? `Namaste, ${title} ${name}` : `Namaste, ${name}`;
}
function finalPrice(amount: number, discount = 0): number {
return amount - discount; // discount is inferred as number
}
function logOrder(id: string): void {
console.log("Order placed:", id); // returns nothing useful
}Inside greet, title has the type string | undefined, because the caller may skip it. A parameter with a default value is also optional, and its type comes from the default.
Describing objects: type and interface
type Product = {
readonly id: string; // cannot be changed after creation
name: string;
price: number;
inStock?: boolean; // optional: may be missing
};
interface Customer {
name: string;
phone: string;
city?: string;
}
const rice: Product = { id: "p1", name: "Basmati rice 1kg", price: 120 };
rice.price = 110; // OK
rice.id = "p2"; // Error: Cannot assign to 'id' because it is a read-only property.| type alias | interface | |
|---|---|---|
| Describe an object | Yes | Yes |
| Name a union like "upi" | "card" | Yes | No |
| Build on another | With & (intersection) | With extends |
| Add fields in a second declaration | No | Yes (declaration merging) |
A simple rule: use type for unions and small shapes, and use either for objects. Pick one style for objects in a project and stay with it. Both are removed when the code runs.
Arrays of objects and callbacks
const cart: Product[] = [
{ id: "p1", name: "Rice", price: 120 },
{ id: "p2", name: "Toor dal", price: 160, inStock: true },
];
function applyToAll(prices: number[], change: (price: number) => number): number[] {
return prices.map(change);
}
applyToAll([100, 200], (p) => p * 1.18); // p is inferred as numberObjects used as dictionaries: Record
const stock: Record<string, number> = { rice: 20, dal: 15 };
stock["sugar"] = 8; // any string key, number values
// The same idea written as an index signature:
type Stock = { [item: string]: number };Watch the lesson
Typing functions and objects · 1/7
function gst(price: number, rate: number): number {
return (price * rate) / 100;
}Give every parameter a type, and write the return type after the brackets.
Prefer a video by a teacher? Find free videos on “typescript functions interfaces type alias tutorial” on YouTube ↗
In real life: A typed cart for a kirana app
A neighbourhood shop app has type CartItem = { productId: string; name: string; price: number; qty: number }. The cart is CartItem[], and functions like cartTotal(items: CartItem[]): number and addItem(cart: CartItem[], item: CartItem): CartItem[] use that one shape. When the team adds a new field, discount?: number, the editor shows every place that may need to handle it.
Practice (0/3 done)
A CartItem has a name (string), a price (number, in rupees) and a qty (number). Write cartTotal(items: CartItem[]): number that returns the sum of price x qty for every item. cartTotal([{ name: "Rice", price: 60, qty: 2 }, { name: "Dal", price: 110, qty: 1 }]) returns 230. An empty cart returns 0.
Write makeLabel(name: string, price: number, currency: string = "Rs", note?: string): string. It returns "<name>: <currency> <price>", and when a note is given it adds " (<note>)" at the end. makeLabel("Rice", 60) returns "Rice: Rs 60". makeLabel("Rice", 60, "INR") returns "Rice: INR 60". makeLabel("Tea", 40, "Rs", "offer") returns "Tea: Rs 40 (offer)".
Each Product has a name and a category (both strings). Write countByCategory(products: Product[]): Record<string, number> that returns how many products are in each category. For [{ name: "Milk", category: "dairy" }, { name: "Curd", category: "dairy" }, { name: "Apple", category: "fruit" }] it returns { dairy: 2, fruit: 1 }. An empty list returns {}.
Quick quiz
Read more (free)
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.