Emmanuel Akinfulubi

TypeScriptClasses and OOP

Student class with name and class in TypeScript

5 A student with a name and a class

easy

Write a student class with a name and a class group. Fill both in through the constructor and add a way to print the student's details.

Stuck? Three hints, smallest first
  1. 1. class is a reserved word, so a property called class needs care; classGroup reads better.
  2. 2. A toString() method makes the object print nicely in template literals and logs.
  3. 3. Keep the fields readonly if nothing should change them after construction.

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 Student {
  constructor(
    public readonly name: string,
    public readonly classGroup: string,
  ) {}

  // Defining toString means the object reads well anywhere text is expected.
  toString(): string {
    return `${this.name} (${this.classGroup})`;
  }

  details(): string {
    return `Name: ${this.name}, Class: ${this.classGroup}`;
  }
}

const one = new Student('Amaka Obi', 'JSS 3');
const two = new Student('Chidi Eze', 'SSS 1');

console.log(one.details());
console.log(`${two}`);          // toString is used here
console.log(String(one));

// readonly is refused at compile time:
// one.name = 'Somebody else';   // Cannot assign to 'name'

test('details', one.details(), 'Name: Amaka Obi, Class: JSS 3');
test('toString via a template literal', `${two}`, 'Chidi Eze (SSS 1)');
test('toString via String()', String(one), 'Amaka Obi (JSS 3)');
test('the field is set', two.classGroup, 'SSS 1');

Output


      

I renamed the second property to classGroup because class is a reserved word in JavaScript; as a property name it is legal but it reads badly and trips people up. The toString() is one line and pays for itself the first time you log a list of these.

Newsletter

New writing, when it lands.

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