TypeScript for real code · Chapter 19 of 36

Classes with types

By the end of this chapter you can write a class whose fields have types and rules: read-only, private, hidden even at runtime, promised by an interface, or left for each subclass to fill in. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: Generics
  • 5 tasks
  • TypeScript
  • In the all labs plan

The first 2 chapters of TypeScript for real code are free. This one comes with the all labs plan.

Why you need this

The evening till at Tapri was ₹1,000 over. Nobody had sold that much chai: Bunty's test script had set till.balance = 1000 directly, and the class let it. Ravi has a second problem: a new kind of rider was added without a speed, so every delivery time for that rider came out as Infinity minutes. And Dev wants the customers' loyalty points out of the JSON the app sends to the analytics service.

Bunty moved Tapri's classes over from the JavaScript app as they were. In JavaScript, "do not touch the balance" and "every rider has a speed" are comments. Nothing checks them, so the mistakes show up as wrong money and wrong times, not as errors.

What you build: 5 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    MenuItem: typed fields, with an id that never changes

    Declare MenuItem's three fields with their types, and type the constructor's parameters: id is a string that can never change after the item is made, name is a string and price is a number. new MenuItem('masala-chai', 'masala chai', 40).label() is 'masala chai ₹40', and its id is 'masala-chai'.

    The price and the name can still be changed later, so only id is readonly. Assigning a new id is a type error, and so is a price written as text, like '40'.

  2. Task 2

    Till: keep the balance private

    Only add may change the till's balance. Make balance private, so till.balance = 1000 is a type error. total stays a getter, so it can be read but not assigned: till.total = 5 is a type error too.

    add(40) then add(25) makes total 65, and add(-5) still throws a RangeError.

  3. Task 3

    UpiPayment and CashPayment: keep the Payment promise

    Both payment classes must be a Payment: a readonly method, exactly 'upi' for UpiPayment and 'cash' for CashPayment, and a pay(amount) that takes a number and returns a string. A list of Payments may hold one of each, and pay('80') is a type error.

    new UpiPayment('meera@okaxis').pay(80) is '₹80 paid by UPI from meera@okaxis', and new CashPayment(100).pay(80) is '₹80 paid in cash, change ₹20'. Say so on each class with implements Payment, and fix what the compiler then finds.

  4. Task 4

    Rider: abstract, so every rider has a speed

    A Rider on its own makes no sense, only a BikeRider (30 km/h) or a CycleRider (12 km/h). Make Rider abstract, with an abstract readonly speedKmph that is a number, so new Rider('Ravi') and a rider class with no speed are type errors, and a rider's speed cannot be assigned.

    new BikeRider('Ravi').etaMinutes(5) is 10, new CycleRider('Kiran').etaMinutes(3) is 15, and new CycleRider('Kiran').name is 'Kiran'.

  5. Task 5 · interview question

    Interview: LoyaltyCard, hide the points even at runtime

    A customer's loyalty points must stay hidden, even from JSON.stringify and Object.keys, and change only through addVisit (10 points a visit). TypeScript's private disappears when the types are removed, so keep the points in a JavaScript #private field instead.

    Keep the points getter: after two visits card.points is 20, JSON.stringify(card) is '{"customer":"Meera"}' and Object.keys(card) is ['customer']. card.points = 500 is a type error. Dev will ask what private does when the file runs.

What you will learn

  • Typed fields and readonly: each field declared with its type, and a field that is set once and never changed.
  • private and #private: a field only the class can touch, checked by TypeScript, or hidden by JavaScript itself when the file runs.
  • implements and abstract: a class that promises an interface's members, and a half-built class whose subclasses must finish it.

More in Generics

Build "Classes with types" yourself

Tapri’s codebase grows, and types keep it honest. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

The first 2 chapters of TypeScript for real code are free. This one comes with the all labs plan.