Emmanuel Akinfulubi

TypeScriptClasses and OOP

Create a class with a constructor in TypeScript

1 A class with three properties and a constructor

easy

Write a class for a bus with a make, a model and a year. Give it a constructor that fills all three in when the object is created.

Stuck? Three hints, smallest first
  1. 1. Declare the fields with their types at the top of the class, then assign them in the constructor.
  2. 2. TypeScript has a shortcut: put public in front of each constructor parameter and it declares and assigns the field for you.
  3. 3. Under strict, a declared field that the constructor never assigns is an error (TS2564).

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)}`)
  );
}

// The long form: declare, then assign.
class Bus {
  make: string;
  model: string;
  year: number;

  constructor(make: string, model: string, year: number) {
    this.make = make;
    this.model = model;
    this.year = year;
  }
}

// The short form. Parameter properties declare and assign in one go.
class BusShort {
  constructor(
    public make: string,
    public model: string,
    public year: number,
  ) {}
}

const a = new Bus('Toyota', 'Coaster', 2019);
const b = new BusShort('Toyota', 'Coaster', 2019);

console.log(a.make, a.model, a.year);
console.log(b.make, b.model, b.year);

test('long form make', a.make, 'Toyota');
test('long form year', a.year, 2019);
test('short form is identical', b.model, 'Coaster');
test('both produce the same data', JSON.stringify(a), JSON.stringify(b));

Output


      

The two classes produce identical objects. Parameter properties save six lines and are the normal choice for a plain data class. Worth knowing that they are a TypeScript feature, not JavaScript: they compile down to the assignments in the first version.

Newsletter

New writing, when it lands.

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