Typing a Class and Its Methods

The league-table script has kept the Riverside Kids’ Football League’s standings for three seasons. The script is built around a small JavaScript class, ResultsTable. Volunteers use it to add the teams, record each weekend’s results, and get a sorted table out. It works, but nothing checks the values that go into it, and its copy of the league’s types has already drifted from the other scripts’ copies.

In this lesson, you’ll turn that class into the first typed piece of the league’s client. You’ll annotate its fields and methods, check it against a shared interface with implements, and see what that check covers and where it stops. Start with the project you’ll build the client in.

Annotate the Results Table

Before you can type the class, you need a project where npm run check can read it. The course’s Sample Code (.zip) download, linked on the course page and in the course overview, has the Riverside project you’ll add code to in every lesson. It needs a current Node.js release with long-term support (LTS), because Node.js runs .ts files from version 22.18 on. Check yours in a terminal:

Language: Shell
$ node --version
v26.13.1

Your version number may differ. If it’s older than 22.18, then update Node.js to the current LTS release first. Then extract the download, move into the riverside-league folder, and install its dependencies with npm:

Language: Shell
$ cd riverside-league
$ npm install

That installs TypeScript, so tsc, the checker, is ready. In package.json, the "check" script runs tsc --noEmit, which checks every .ts file and writes nothing. The project’s tsconfig.json turns on strict mode. The folder also holds server.mjs, a small stand-in for the league’s API. You’ll start it once the client makes its first request, so leave it alone for now.

Create results-table.ts and paste in the class from the league-table script, with a few lines at the bottom that try it out:

Language: TypeScript Filename: results-table.ts
 1function score(scored, conceded) {
 2  if (scored > conceded) return 3;
 3  return scored === conceded ? 1 : 0;
 4}
 5
 6class ResultsTable {
 7  constructor(season) {
 8    this.season = season;
 9    this.rows = [];
10  }
11
12  addTeam(team) {
13    this.rows.push({ team, points: 0 });
14  }
15
16  recordResult(result) {
17    const { home, away, homeGoals, awayGoals } = result;
18    for (const row of this.rows) {
19      if (row.team === home) row.points += score(homeGoals, awayGoals);
20      if (row.team === away) row.points += score(awayGoals, homeGoals);
21    }
22  }
23
24  standings() {
25    return this.rows.toSorted((a, b) => b.points - a.points);
26  }
27}
28
29const table = new ResultsTable("Fall 2026");
30table.addTeam("Riverside Lions");
31table.addTeam("Mill Lane Otters");
32table.addTeam("Kestrel Park");
33table.recordResult({
34  home: "Kestrel Park", away: "Riverside Lions",
35  homeGoals: 1, awayGoals: 3,
36});
37table.recordResult({
38  home: "Mill Lane Otters", away: "Kestrel Park",
39  homeGoals: 2, awayGoals: 2,
40});
41for (const row of table.standings()) {
42  console.log(`${row.team}: ${row.points}`);
43}

A win is worth three points and a draw one. The score() function works that out from the goals one team scored and conceded, and .recordResult() adds the points to both teams’ rows. The .standings() method returns a sorted copy with .toSorted(), so a caller can’t reorder the table’s own rows. Run the file:

Language: Shell
$ node results-table.ts
Riverside Lions: 3
Mill Lane Otters: 1
Kestrel Park: 1

The Lions won away, and the other two drew, so the table is right. That’s plain JavaScript, so Node.js runs it as it is. Now run npm run check, and the checker has a dozen complaints:

Language: Shell
$ npm run check

> [email protected] check
> tsc --noEmit

results-table.ts:1:16 - error TS7006: Parameter 'scored' implicitly has an 'any' type.

1 function score(scored, conceded) {
                 ~~~~~~

...

results-table.ts:8:10 - error TS2339: Property 'season' does not exist on type 'ResultsTable'.

8     this.season = season;
           ~~~~~~

...

Found 12 errors in the same file, starting at: results-table.ts:1

The errors come in two kinds. TS7006 is the one you know from functions: a parameter without a type is any, and strict mode won’t let that slide.

TS2339 is new for classes. In JavaScript, assigning to this.season in the constructor creates the property. In a .ts file, the checker doesn’t create properties from this.season = ....

It only knows the fields declared in the class body, so you need to declare each field there. The checker can often infer a field’s type from what the constructor assigns, but an annotation states the type you intend, so you’ll write one for each field here.

Fix the complaints in three small edits, from the top of the file down. First, the class works with two shapes, a match result and a row of the table, so name them. Add the two type aliases at the very top of the file. The last line of the snippet replaces the existing function score(scored, conceded) { line and gives score() its parameter types:

Language: TypeScript
type MatchResult = {
  home: string;
  away: string;
  homeGoals: number;
  awayGoals: number;
};

type TeamRow = { team: string; points: number };

function score(scored: number, conceded: number) {

Second, declare the fields. The class ResultsTable { line below stays as it is. Add the two lines under it at the top of the class body, each a name and a type, the way you’d write a property in an object type. Then replace the constructor’s first line with the annotated one shown last:

Language: TypeScript
class ResultsTable {
  season: string;
  rows: TeamRow[];

  constructor(season: string) {

The constructor still assigns both fields, and the checker confirms it does.

Third, annotate the methods’ parameters as you would a function’s, using string and the MatchResult shape you named above. Each line below replaces the first line of its method:

Language: TypeScript
  addTeam(team: string) {

The second method takes a whole result:

Language: TypeScript
  recordResult(result: MatchResult) {

You can leave the return types to inference. The checker works out that .standings() returns a TeamRow[], and it already knows a and b in the .toSorted() callback are rows. Run npm run check again, and it’s clean.

One field deserves a stronger promise. A table belongs to one season, so nothing should change .season once the table exists.

Put readonly in front of it on line 16, so it reads readonly season: string;. The checker then reports any reassignment outside the class’s constructor. You can confirm it by adding table.season = "Spring 2027"; above the for loop. The checker now reports an error on line 53:

Language: Shell
results-table.ts:53:7 - error TS2540: Cannot assign to 'season' because it is a read-only property.

53 table.season = "Spring 2027";
         ~~~~~~

Like the type annotations, readonly is a check only. Node.js strips it with the types, so the file still runs and the assignment still happens. Delete that line before you go on. Note, too, that readonly protects only the field itself. A readonly rows would still let .push() add a row to the array.

If you’d like to compare your file with the whole typed version, open it below. The highlighted lines are the ones that changed, and the test lines at the bottom stay as they were.

Language: TypeScript Filename: results-table.ts
 1type MatchResult = {
 2  home: string;
 3  away: string;
 4  homeGoals: number;
 5  awayGoals: number;
 6};
 7
 8type TeamRow = { team: string; points: number };
 9
10function score(scored: number, conceded: number) {
11  if (scored > conceded) return 3;
12  return scored === conceded ? 1 : 0;
13}
14
15class ResultsTable {
16  readonly season: string;
17  rows: TeamRow[];
18
19  constructor(season: string) {
20    this.season = season;
21    this.rows = [];
22  }
23
24  addTeam(team: string) {
25    this.rows.push({ team, points: 0 });
26  }
27
28  recordResult(result: MatchResult) {
29    const { home, away, homeGoals, awayGoals } = result;
30    for (const row of this.rows) {
31      if (row.team === home) row.points += score(homeGoals, awayGoals);
32      if (row.team === away) row.points += score(awayGoals, homeGoals);
33    }
34  }
35
36  standings() {
37    return this.rows.toSorted((a, b) => b.points - a.points);
38  }
39}
40
41const table = new ResultsTable("Fall 2026");
42table.addTeam("Riverside Lions");
43table.addTeam("Mill Lane Otters");
44table.addTeam("Kestrel Park");
45table.recordResult({
46  home: "Kestrel Park", away: "Riverside Lions",
47  homeGoals: 1, awayGoals: 3,
48});
49table.recordResult({
50  home: "Mill Lane Otters", away: "Kestrel Park",
51  homeGoals: 2, awayGoals: 2,
52});
53for (const row of table.standings()) {
54  console.log(`${row.team}: ${row.points}`);
55}

Check the Class Against an Interface

The results table won’t be the client’s only table. A summer tournament’s table or the under-8s’ fair-play table could be printed and published the same way, so the client describes what any table must offer in one shared type. The league’s TableSource is an interface, another way to write an object type you’ve seen in other people’s code. Add it below TeamRow, at line 10:

Language: TypeScript
interface TableSource {
  readonly season: string;
  recordResult(result: MatchResult): void;
  standings(): TeamRow[];
}

The two lines with parentheses describe methods: .recordResult() takes a MatchResult and returns nothing useful (void), and .standings() returns rows. Later, this interface moves into a module of its own, but for now it sits at the top of this file.

To say that ResultsTable is meant to fit this shape, add implements TableSource to the class’s first line, now line 21:

Language: TypeScript
class ResultsTable implements TableSource {

The implements clause asks the checker to compare the class with the interface, member by member, and report anything that doesn’t fit. The check is clean, because the class already has all three members. To see what it reports when one is missing, rename .standings() on line 42 to .sorted(), and the call on line 59 with it:

Language: Shell
results-table.ts:21:7 - error TS2420: Class 'ResultsTable'
incorrectly implements interface 'TableSource'.
  Property 'standings' is missing in type 'ResultsTable' but required in type 'TableSource'.

21 class ResultsTable implements TableSource {
         ~~~~~~~~~~~~

  results-table.ts:13:3 - 'standings' is declared here.
    13   standings(): TeamRow[];
         ~~~~~~~~~~~~~~~~~~~~~~~

Read it from the top (its first line is wrapped for display). The error appears at the class’s name on line 21, and the indented line under it names the missing member. The last part points to line 13, where the interface asks for it.

The implements clause doesn’t add a .standings() method, and Node.js still runs the file. The clause only checks the class you wrote, so you write every member yourself. Rename the method and its call back to .standings().

Since the interface already says .recordResult() takes a MatchResult, do you still need the annotation on line 34? Predict what npm run check says if you change that line back to recordResult(result) {, and then try it.

The checker still asks for the annotation:

Language: Shell
results-table.ts:34:16 - error TS7006: Parameter 'result' implicitly has an 'any' type.

34   recordResult(result) {
                  ~~~~~~

The implements clause doesn’t pass the types in the interface on to the methods in the class. The checker types the class from its own code first, and only then compares it with TableSource. Without an annotation, result is any, and strict mode reports that before any comparison. So you write the parameter types twice, once in the interface and once in the class.

The implements check catches a parameter type that doesn’t fit the interface’s, such as result: number where the interface says MatchResult, but it doesn’t make the two types identical.

Put result: MatchResult back on line 34 so the check is clean again. If you’d like to test where implements stops before moving on, the button below opens a chat with the mentor and sends this request for you. Expect one short case at a time, each asking you to say whether the check passes:

Want to test where implements stops?

Use the Class Name as a Type

The test lines at the bottom print the standings, and the league’s website will need the same printout for every table. That’s a job for a function, and its parameter needs a type. A class’s name is also a type: ResultsTable in a type position means “an instance of this class.” Replace the for loop at the bottom with a function and a call:

Language: TypeScript
function printTable(table: ResultsTable) {
  for (const row of table.standings()) {
    console.log(`${row.team}: ${row.points}`);
  }
}

printTable(table);

The check is clean, and node results-table.ts prints the same three lines as before. The name now does two jobs. As a value, ResultsTable is the class you call with new, and it’s still there when Node.js runs the file. As a type, it’s the shape of its instances, and it’s gone with the other types.

As with the object types you’ve used, the checker compares that type by structure, provided the class has no private or protected members. This one has none, so any object with the members of ResultsTable fits, whether new ResultsTable() made it or not. You’ll meet TypeScript’s private in the next lesson, so that’s all you need about those members for now.

Still, printTable() only uses .standings(), so ResultsTable asks for more than the function needs. Change the parameter to table: TableSource, and you can print any table that implements the interface, including the summer tournament’s. That’s the usual reason to share an interface. Code that uses a table asks for the interface, and each class checks itself against it with implements.

You’ll choose between the class and the interface often, so it helps to put the choice into your own words. The button below opens a chat with the mentor with this question filled in. Try explaining the choice you made for printTable(), and the mentor will ask follow-up questions or point out a case you missed:

Whatever you discussed, the choice comes down to the members a function uses. The printTable() function calls only .standings(), which TableSource promises, so the interface is enough. A function that called .addTeam(), which the interface doesn’t list, would need ResultsTable.

You may also meet abstract class in other code: a class the checker won’t let you call with new. It exists to be extended and can leave methods for its subclasses to write. Like readonly, abstract is erased, so Node.js wouldn’t stop a new call. This course shares shapes with interfaces instead, so that’s all you need about abstract classes for now.

Check Your Understanding

Try these before you open the answers. They use the results-table.ts you built.

  1. A volunteer adds this method to the class: removeTeam(team) { this.rows = this.rows.filter((row) => row.team !== team); }. What does it need before npm run check is clean, and would it still work if .rows were readonly?
  2. The league adds teamCount(): number to TableSource. What does npm run check report, and where does the fix go?
  3. A teammate says, “The class implements TableSource, so I can drop the parameter annotations in its methods.” What do you tell them?
  1. It needs a type on team, such as removeTeam(team: string), or the checker reports TS7006. The rest is already typed, because the checker knows this.rows is a TeamRow[]. With readonly rows, the assignment this.rows = ... would fail with TS2540, because .filter() makes a new array and the method assigns it to the field. A readonly field can’t be reassigned outside the constructor.
  2. It reports TS2420 on the class’s name: ResultsTable incorrectly implements TableSource, because .teamCount() is missing. The fix goes in the class: you write a .teamCount() method that returns this.rows.length. The implements clause never adds it for you.
  3. That doesn’t work. The checker types each method from the class’s own code, so a parameter without an annotation is any, and strict mode reports TS7006. The interface’s types aren’t copied into the class: implements only compares the two.

You now have a typed ResultsTable that the checker holds to TableSource. The next lesson is the video Keeping Fields Private at Run Time. In it, a volunteer adds each coach’s phone number, for match-day calls, to the small Team class behind the website’s team list and marks that field private. You’ll find out there what the keyword does and doesn’t protect.

Become a Member to join the conversation.