Emmanuel Akinfulubi

TypeScriptClasses and OOP

Add a method to a class in TypeScript

2 Adding a method that reports on the object

easy

Take the bus class and add a start() method that returns a message saying it is starting. Show that the method is shared between instances rather than copied into each one.

Stuck? Three hints, smallest first
  1. 1. A method goes in the class body with no function keyword: start(): string { ... }.
  2. 2. Inside the method, this is the instance the method was called on.
  3. 3. Methods live on the prototype, so a.start === b.start is true.

The answer, and proof it works

const same = (a: unknown, b: unknown): boolean =>
  JSON.stringify(a) === JSON.stringify(b);

function test(name: string, got: unknown, want: unknown): void {
  console.log(
    (same(got, want) ? 'ok   ' : 'FAIL ') + name +
    (same(got, want) ? '' : `  got ${JSON.stringify(got)}, want ${JSON.stringify(want)}`)
  );
}

class Bus {
  constructor(
    public make: string,
    public model: string,
    public year: number,
  ) {}

  start(): string {
    return `${this.make} ${this.model} (${this.year}) is starting`;
  }

  describe(): string {
    return `${this.year} ${this.make} ${this.model}`;
  }
}

const a = new Bus('Toyota', 'Coaster', 2019);
const b = new Bus('Mercedes', 'Sprinter', 2021);

console.log(a.start());
console.log(b.start());

// One copy of the method, shared by every instance.
const shared = a.start === b.start;
const onPrototype = Object.hasOwn(Bus.prototype, 'start');
const ownKeys = Object.keys(a);

console.log('same function object?', shared);
console.log('the instance owns only data:', ownKeys);

test('start message', a.start(), 'Toyota Coaster (2019) is starting');
test('the other instance', b.start(), 'Mercedes Sprinter (2021) is starting');
test('describe', a.describe(), '2019 Toyota Coaster');
test('methods are shared', shared, true);
test('start lives on the prototype', onPrototype, true);
test('instances hold data only', ownKeys, ['make', 'model', 'year']);

Output


      

The last two assertions are the point. Data lands on the instance, behaviour lands on the prototype, and every instance borrows the one copy. That is why Object.keys(a) lists only the three fields.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.