Skip to content
Tutorials Center
My learning

Topics

Lesson 86 of 96 ยท Projects

Project: Typing Speed Test

Build a typing speed test in TypeScript - score text per character, compute WPM and accuracy, run a timed session state machine with an injectable clock, and bind it to DOM events.

A typing speed test shows you a passage, starts a timer when you type the first key, and reports your speed in words per minute (WPM) and your accuracy when time runs out. It is a great TypeScript exercise because it mixes pure logic (scoring), time (timers you can't wait for in a test) and the DOM (input events), and each of them needs a different kind of typing.

You will build it in three stages. First the scoring functions, which need no browser. Then a session controller that depends on a clock interface instead of the real setTimeout, so you can run a whole 30 second test in a few milliseconds. Finally the DOM wiring, using the same DOM-shaped interface trick as in Project: DOM Widgets.

Stage 1: scoring

Compare what the user typed with the target text character by character. Each character of the target gets a state: correct, incorrect or pending (not typed yet). Anything typed beyond the end of the target is an extra character.

By convention, one "word" is 5 characters, which makes WPM independent of word length: WPM = (correct characters / 5) / minutes.

TypeScript Stage 1: per-character state, WPM and accuracy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Look at how the result type is built. Every field is readonly, so a score is a snapshot nobody can tamper with, and CharState is a literal union, so the renderer can later switch over it exhaustively (for example to pick a CSS class). The guard in wordsPerMinute avoids dividing by zero, which would produce Infinity.

Stage 2: the session and an injectable clock

A test has phases: idle (waiting for the first key), running (the countdown is ticking) and finished. That is a discriminated union whose members carry only the data valid for that phase, so you cannot read endedAt while the test is still running.

The hard part of a timed feature is time itself. If your class calls setInterval directly, every test takes real seconds and is flaky. The fix is dependency injection: the class receives a small Clock interface. In production you pass the real timers. In tests you pass a fake whose time you control.

TypeScript Stage 2: a session controller driven by a fake clock

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Several type-level ideas are at work:

  • The Phase union means startedAt is only accessible after narrowing with this.phase.kind === 'running'. TypeScript will not let you read it in the idle state.
  • Parameters<Listener>[0] extracts the event type from the listener's signature so emit and onEvent can never disagree.
  • private readonly constructor parameters declare the fields in one line (see Classes).
  • The Clock interface is structural: the real window object nearly satisfies it, and a three-line wrapper completes the job.

Stage 3: DOM events

Now connect the session to the page. As before, the DOM is described by the smallest interfaces that suit us. The passage is shown as <span> elements whose class comes from the character state, and an <input> or <textarea> supplies keystrokes through its input event.

TypeScript Stage 3: rendering and input events through DOM-shaped interfaces

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Two real-world lessons are hidden here. The passage is turned into HTML, so every character goes through escapeHtml; otherwise a target such as a<b & c would break the markup, and a malicious string could inject elements (see the security notes in DOM and TypeScript). And the controller is returned as a small read-only handle, { typed }, so callers can read state but not change it.

In a browser, you would add a one-time setInterval wrapper that satisfies Clock:

TypeScript
const browserClock: Clock = {
  now: () => performance.now(),
  setInterval: (callback, ms) => window.setInterval(callback, ms),
  clearInterval: (id) => window.clearInterval(id),
};

const input = document.querySelector<HTMLTextAreaElement>('#typing-input');
const passage = document.querySelector<HTMLElement>('#passage');
const status = document.querySelector<HTMLElement>('#status');

if (input && passage && status) {
  mount({ input, passage, status }, 'the quick brown fox jumps over the lazy dog');
}

The if narrows the three querySelector results (each is T | null) in one go.

Ideas to extend it

  • Show a live WPM that updates on every tick, using wordsPerMinute from stage 1.
  • Choose a random passage from a readonly string[] using the secure pick from Project: Password Generator and Unicode Finder.
  • Keep a readonly Score[] history and highlight your personal best.
  • Add difficulty levels as a literal union, mapped to durations with a Record.
  • Count the most-mistyped characters in a Map<string, number>.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does TypingSession receive a Clock instead of calling setInterval directly?

    Dependency injection lets a fake clock replace real time, making time-based code fast and deterministic to test.
  2. 2. How is WPM calculated in this project?

    A standard word is five characters, so the formula does not depend on how long the words are.
  3. 3. What does the Phase discriminated union prevent?

    Only the running member has startedAt; TypeScript requires you to narrow before reading it.
  4. 4. Why does renderPassage call escapeHtml for each character?

    Characters are inserted via innerHTML, so they must be escaped.
  5. 5. What does Parameters<Listener>[0] give you?

    Parameters<F> is a tuple of F's parameter types; indexing [0] selects the first.

Summary

  • Score text per character with a literal-union CharState; WPM is (correct / 5) / minutes and must guard against zero time.
  • Model a timed session as a discriminated union of phases so each phase exposes only valid data.
  • Inject a Clock interface so time-dependent code can be tested with a fake clock.
  • Use Parameters<F>[0] to derive event types from listener signatures.
  • Bind to the DOM through small structural interfaces, and escape any text you insert with innerHTML.

Next: Project: Pixel Art Maker