Learn/TypeScript/10. Structuring data
Lesson 10 of 15
Sign in

TypeScript, lesson 10

Structuring data

Programs get easier to read when their data has names and shapes. TypeScript lets you describe the shape of an object once and reuse that description everywhere, and its classes add access control on top of JavaScript classes.

Interfaces and type aliases

An interface names an object shape:

A type alias can describe the same shape, type Book = { ... }, and can also name unions, tuples and function types, which interfaces cannot. Many teams use interfaces for object shapes and type for everything else; either choice is fine if you are consistent.

TypeScript compares shapes, not names. This is called structural typing: any object with the right properties counts as a Book, whether or not it was declared as one. But an object literal with an extra, unexpected property is flagged, because that is usually a typo.

Optional properties have type , so the checker makes you handle the missing case: uses , which stops and gives when is missing instead of crashing.

2 exercises to try what you just read.

Exercise 1

Shopping cart

Press Ctrl Enter or Check to test your code.

Exercise 2

Shape report

Press Ctrl Enter or Check to test your code.

T | undefined
book.subtitle?.toUpperCase()
optional chaining
undefined
subtitle

Classes

  • Fields are declared with their types at the top of the class.
  • private hides a member from code outside the class; readonly allows assignment only in the constructor. Both are checked by TypeScript at compile time only. JavaScript's own #field syntax gives true run-time privacy if you need it.
  • static members belong to the class itself: Thermostat.MAX.
  • A get accessor is read like a property: t.setting.

TypeScript also has a shorthand, parameter properties: writing constructor(private target: number) declares and assigns the field in one go. Deno supports it, but some tools that strip types without compiling do not, so this course spells fields out.

Classes that implement interfaces

An interface can describe what a class must provide. implements asks TypeScript to check it:

Code that works with Shape values does not care which class made them; anything with a name and an area() will do. This is how you write functions that work for many kinds of objects.

Plain objects or classes?

Use interfaces with plain objects for data that is just data, such as a parsed input line. Use a class when the data has rules to protect (like "target never exceeds 30") or behaviour that belongs with it.

Further reading

  • TypeScript Handbook: Object Types
  • TypeScript Handbook: Classes
  • TypeScript Handbook: Everyday Types, interfaces vs type aliases
  • MDN: Optional chaining

Write a class Cart that keeps a private list of LineItem objects (the interface is given) and has:

  • add(name: string, price: number, qty: number): void: if the item is already in the cart, increase its quantity; otherwise add a new line item.
  • remove(name: string): boolean: removes the item completely and returns true, or returns false if it was not there.
  • a getter total returning the sum of price * qty over all items.
  • a getter count returning the total quantity of all items.

The main program is given. It reads commands (add NAME PRICE QTY, remove NAME, total) and prints results.

Sample input:

Sample output:

The Shape interface is given. Write three classes that implement it: Circle (radius), Rectangle (width, height) and Triangle (base, height, area is half of base times height). Each has a name (circle, rectangle, triangle) and an area() method. Then write parseShape(line: string): Shape that builds the right object from a line like circle 2, rectangle 3 4 or triangle 6 2.

The given main program prints each shape with its area to two decimals, then the name of the largest shape (the first one if there is a tie).

Sample input:

Sample output:

interface Book {
  title: string;
  author: string;
  pages: number;
  subtitle?: string;          // optional: may be missing
  readonly isbn: string;      // cannot be reassigned after creation
}

const book: Book = { title: "Dune", author: "Herbert", pages: 412, isbn: "978-0441" };
book.pages = 600;             // fine
book.isbn = "x";              // error: isbn is read-only
class Thermostat {
  readonly room: string;
  private target: number;
  static readonly MAX = 30;

  constructor(room: string, target = 20) {
    this.room = room;
    this.target = target;
  }

  raise(by: number): void {
    this.target = Math.min(this.target + by, Thermostat.MAX);
  }

  get setting(): string {
    return `${this.room}: ${this.target} C`;
  }
}

const t = new Thermostat("kitchen");
t.raise(15);
console.log(t.setting);   // kitchen: 30 C
t.target = 5;             // error: 'target' is private
interface Shape {
  name: string;
  area(): number;
}

class Square implements Shape {
  name = "square";
  side: number;

  constructor(side: number) {
    this.side = side;
  }

  area(): number {
    return this.side ** 2;
  }
}
add apple 0.5 4
add bread 2.2 1
add apple 0.5 2
total
remove milk
remove bread
total
7 items, 5.20
milk not in cart
6 items, 3.00
circle 1
rectangle 3 4
triangle 6 2
circle 3.14
rectangle 12.00
triangle 6.00
largest: rectangle