Skip to content

Expert · TypeScript basics · topic 52 of 64 · 35 min

Typing functions and objects

Explanation

Give every function parameter a type, and say what the function returns. Describe the shape of your objects once, with a type alias or an interface, and reuse that name everywhere: Product, CartItem, Customer. Then TypeScript catches a missing field or a typo in a property name at once.

Parameter and return types

typescript
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'.
Types after each parameter; the return type after the brackets

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

typescript
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
}
title? may be left out; discount has a default; void means "no useful return value"

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

Think of it like this: A type for an object is like the printed format of a college ID card. Every card has the same boxes in the same places: name, roll number, branch, photo. The values differ from student to student, but the shape is always the same, so anyone can read any card.
typescript
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.
A type alias and an interface both describe an object shape
type aliasinterface
Describe an objectYesYes
Name a union like "upi" | "card"YesNo
Build on anotherWith & (intersection)With extends
Add fields in a second declarationNoYes (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

typescript
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 number
Product[] is a list of products; (price: number) => number is the type of a callback

Objects used as dictionaries: Record

typescript
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 };
Record<string, number> means "keys are strings, values are numbers"
Tip: Name your types with a capital first letter (Product, CartItem) and keep shared types in one place, such as a types.ts file, so every part of the app uses the same shape.
Careful: With Record<string, number>, stock["salt"] has the type number, but at runtime it is undefined if there is no salt. Check before you use it, or turn on the noUncheckedIndexedAccess option so TypeScript adds | undefined for you.

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)

Task 1 · Code · Typescript

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.

Task 2 · Code · Typescript

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)".

Task 3 · Code · Typescript

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

Question 1

1.function greet(name: string, title?: string) { ... } Inside the function, what is the type of title?

Question 2

2.What does a return type of void mean?

Question 3

3.type Product = { readonly id: string; price: number }; const p: Product = { id: "p1", price: 50 }; Which line is an error?

Question 4

4.Which type fits an object like { rice: 20, dal: 15, sugar: 8 } where the item names can be anything?

Question 5

5.Which of these can a type alias do that an interface cannot?

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.

← Previous: Why TypeScript