Emmanuel Akinfulubi

TypeScriptModules and namespaces

Export and import a class in TypeScript

2 Export a class, then build instances elsewhere

easy

Write a module exporting a student class with a name and an age. Import it into another file, create a couple of students and print their details.

Stuck? Three hints, smallest first
  1. 1. A class is exported the same way a function is: export class Student { ... }.
  2. 2. You can export the type as well as the class; a class name is both a value and a type.
  3. 3. Give it a toString() so printing a student reads well.

The real answer, across 2 files. Type-checked by the compiler at build time; not runnable in a browser, because a panel cannot contain import or export.

student.ts

export class Student {
  constructor(
    public readonly name: string,
    public readonly age: number,
  ) {}

  describe(): string {
    return `${this.name}, ${this.age}`;
  }

  toString(): string {
    return this.describe();
  }
}

// A type alias can travel with it.
export type StudentList = readonly Student[];

roll.ts

import { Student, type StudentList } from './student.js';

const roll: StudentList = [
  new Student('Amaka Obi', 17),
  new Student('Chidi Eze', 18),
];

for (const s of roll) console.log(s.describe());

// A class name is a value AND a type, so this is legal:
const first: Student = roll[0]!;
console.log(String(first));

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 class itself needs no module syntax, so this part is the real thing.
class Student {
  constructor(
    public readonly name: string,
    public readonly age: number,
  ) {}

  describe(): string {
    return `${this.name}, ${this.age}`;
  }

  toString(): string {
    return this.describe();
  }
}

type StudentList = readonly Student[];

const roll: StudentList = [
  new Student('Amaka Obi', 17),
  new Student('Chidi Eze', 18),
];

for (const s of roll) console.log(s.describe());
console.log('printed via toString:', `${roll[0]}`);

test('two students on the roll', roll.length, 2);
test('describe', roll[0]?.describe(), 'Amaka Obi, 17');
test('toString is used in a template', `${roll[1]}`, 'Chidi Eze, 18');
test('readonly array rejects push at compile time', Array.isArray(roll), true);
test('the class name works as a type too', roll[0] instanceof Student, true);

Output


      

Note import { Student, type StudentList } in the reference. The type keyword inside the braces says "this one is only a type, erase it". Useful because a class is both a value and a type, and being explicit stops bundlers keeping code they do not need.

Newsletter

New writing, when it lands.

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