Menu

Your First TypeScript Program

Lesson 4: Your First TypeScript Program

What does a typed program look like?

Part Syntax Example
Typed variable name: type = value let stock: number = 25;
Typed parameter (param: type) (price: number)
Return type (): type function total(): number
Object type { key: type } { name: string; price: number }
Array type type[] string[]

Example

// src/cart.ts
type CartItem = {
  name: string;
  price: number;   // in rupees
  quantity: number;
};

const cart: CartItem[] = [
  { name: 'Basmati Rice 5kg', price: 645, quantity: 1 },
  { name: 'Milk 1L', price: 64, quantity: 3 },
  { name: 'Bananas (dozen)', price: 60, quantity: 2 },
];

function getCartTotal(items: CartItem[]): number {
  return items.reduce((sum, item) => sum + item.price * item.quantity, 0);
}

const total = getCartTotal(cart);
console.log(`Cart total: ₹${total}`); // Cart total: ₹957

How it works

  • CartItem describes the shape every cart item must have.
  • cart: CartItem[] means "an array of CartItem objects". Adding { name: 'Eggs' } without a price is an error.
  • getCartTotal accepts only CartItem[] and must return a number.
  • total has no annotation, but TypeScript infers it is a number from the function's return type.
  • Inside reduce, the editor knows item is a CartItem, so typing item. lists name, price, and quantity.

Common mistakes

Mistake Error Fix
Misspelling a property (item.prise) Property 'prise' does not exist Use autocomplete
Missing a required property Property 'price' is missing Add it, or make it optional (Module 3)
Annotating everything, even obvious values Noisy code Let TypeScript infer simple values

Key takeaways

  • Annotate function parameters and shared data shapes; let TypeScript infer the rest.
  • Types turn your editor into a guide that suggests properties and flags mistakes.

Try it: Add a discount function that takes a total and a percentage and returns the discounted amount. Call it with a string and read the error.


TypeScript Tutorial

J

Jebasta





Get in Touch For Details