TypeScript and React course Lesson 3 of 6

TypeScript from zero: a class bundles the method

A class holds the fields and the method together. new Item makes a latte. label prints latte $4.50.

Arthur is one of GoByte's characters. This post was drafted by AI agents in Arthur's voice, then fact checked, run and edited by the GoByte team.

Back to top

A type describes a value. A class builds one. The constructor stores the fields. The method reads them off this, which is the object you called the method on.

The class is the runtime object#

A class exists at runtime, unlike a type alias. new Item allocates the object and runs the constructor, which stores the two arguments on this. label reads this and returns a string. The return type is checked. The fields are public in this lesson, so a caller can also read latte.cents directly. The method is the behavior you are meant to call. The constructor is the only place the object is assembled.

new builds the object the method closes over
  1. namestringlatte
  2. centsnumber450
  3. label()stringlatte $4.50
class Item {
  name: string;
  cents: number;

  constructor(name: string, cents: number) {
    this.name = name;
    this.cents = cents;
  }

  label(): string {
    const frac = String(this.cents % 100).padStart(2, "0");
    return this.name + " $" + Math.floor(this.cents / 100) + "." + frac;
  }
}

const latte = new Item("latte", 450);
console.log(latte.label());
latte $4.50

new runs the constructor#

new Item("latte", 450) makes an object and runs constructor. this.name = name stores the argument on that object. Afterward latte.name is "latte" and latte.cents is 450. latte.label() calls the method with latte as this and returns latte $4.50.

The field lines name: string and cents: number are the class's record of the types. A constructor that forgot this.cents = cents would leave cents unset, and with strict checks the class would not compile. Assign every field in the constructor.

The method travels with the data#

label does not take the name and the price as arguments. They are already on this. A second new Item("tea", 250) has its own fields, and tea.label() reads those. The next lesson is the tip about changing a field without losing the old object.

Report a mistake

Your product here? Partner with us

Back to top

Discussion

No comments yet. Signed in GoByte members with a verified e-mail can join. Community guidelines

Reading is open to everyone. Commenting and voting need a GoByte account with a verified e-mail.