Menu

Classes and Types

Lesson 1: Classes and Types

What does TypeScript add to classes?

Feature JavaScript TypeScript
Fields Declared, untyped Declared with types
Constructor parameters Untyped Typed
Uninitialised fields Allowed (undefined) Error under strict unless initialised
Class as a type No Yes: let c: Cart
Access modifiers #private only public, private, protected, plus #private

Example

type CartItem = { productId: string; name: string; price: number; quantity: number };

class Cart {
  items: CartItem[] = [];
  couponCode?: string;
  static readonly FREE_DELIVERY_ABOVE = 49900; // paise

  constructor(public readonly customerId: string) {}

  add(item: CartItem): void {
    const existing = this.items.find((i) => i.productId === item.productId);
    if (existing) existing.quantity += item.quantity;
    else this.items.push(item);
  }

  get subtotal(): number {
    return this.items.reduce((sum, i) => sum + i.price * i.quantity, 0);
  }

  get deliveryFee(): number {
    return this.subtotal >= Cart.FREE_DELIVERY_ABOVE ? 0 : 4000;
  }
}

const cart = new Cart('c7');
cart.add({ productId: 'p1', name: 'Milk 1L', price: 6400, quantity: 2 });
console.log(cart.subtotal, cart.deliveryFee); // 12800 4000

How it works

  • Fields must be initialised in their declaration or the constructor (strictPropertyInitialization). Mark truly optional fields with ?.
  • Getters (get subtotal()) are read like properties: cart.subtotal.
  • static members belong to the class, not instances: Cart.FREE_DELIVERY_ABOVE.
  • The class name is also a type, so function checkout(cart: Cart) accepts any object with the same shape (structural typing still applies).

Common mistakes

Mistake Effect Fix
Declaring a field without initialising it "Property has no initializer" error Initialise it, set it in the constructor, or mark it optional
Using field!: Type to silence the error Runtime undefined Only use ! when a framework truly sets it later
Losing this when passing methods as callbacks this is undefined Use arrow-function properties or .bind

Key takeaways

  • TypeScript classes are JavaScript classes with typed fields, parameters, and returns.
  • Every non-optional field must be initialised.

Try it: Add remove(productId: string) and a total getter (subtotal plus delivery fee) to the Cart class.


TypeScript Tutorial

J

Jebasta





Get in Touch For Details