Skip to content
Tutorials Center
My learning

Topics

Lesson 88 of 96 ยท Projects

Project: Typed Quiz App

Build a quiz engine in TypeScript - model single, multiple, true/false and text questions as a discriminated union, score them with a mapped type, run a session and render results.

A quiz app seems simple until you add a second kind of question. A multiple choice question has one correct option. A "select all that apply" question has several. A true/false question has no options at all, and a fill-in-the-blank question needs text comparison. If you store them all in one loose object with optional fields, every function has to ask "which fields are valid here?". TypeScript has a precise answer: a discriminated union.

In this project you will model four question types, derive the right answer type for each automatically, score answers with a mapped type of scoring functions (so adding a question type forces you to write its scorer), run a session with progress and results, and render questions with exhaustive checks. The concepts come from Discriminated Unions, Mapped Types and Utility Types.

Stage 1: questions, answers and scoring

Each question type has a literal type tag and only the fields it needs. The answer a learner gives also depends on the type: an option index, a set of indexes, a boolean or a string.

TypeScript Stage 1: question types, derived answer types and scorers

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.

The mapped type Scorers is the heart of this design. If you add a fifth question type (say, 'ordering'), TypeScript immediately reports that scorers is missing an entry. And Extract<Question, { type: K }> narrows the question type inside each scorer: in the single scorer q.correct is a number, in the multiple one it is readonly number[], with no casts.

The generic score function relates the question and the answer so a mismatched pair is a compile error (the commented line). The single as cast inside is the price of indexing a mapped type by a generic key; it is contained in one place.

Stage 2: the quiz session

A session holds the questions, the learner's answers so far and the current position. It needs to expose progress, accept answers, and produce a result with a grade. We shuffle the questions with a seeded random generator so that the output here is reproducible, which also makes tests easy.

TypeScript Stage 2: a session with progress, shuffling and results

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.

The session class keeps its questions array private and readonly, so outside code can't reorder or edit it, and finish() returns a readonly snapshot. The Answer union here is looser than the AnswerByType map from stage 1 because the session stores answers of mixed types in one Map; isCorrect re-narrows by switching on q.type and checking the answer's runtime shape with typeof and Array.isArray. That is a common trade-off: precise types at the edges, a union in the middle, validation where the two meet.

Stage 3: rendering with exhaustive checks

Rendering must handle every question type, and a never check makes TypeScript tell you when it doesn't. We produce HTML strings so the output is testable; a framework would produce elements, but the type shape is the same.

TypeScript Stage 3: an exhaustive renderer with escaping

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.

The default branch calls assertNever(q). As long as all four members are handled, q is never there and the call type-checks. Add a 'ordering' member without a case, and the compiler reports an error on that line: the union is the checklist and the compiler is the reviewer. The text in prompts and options goes through escapeHtml because quiz content may come from a file or a database, and <b> in a prompt must display as text, not turn into markup.

Connecting this to a page takes a handful of lines: put the HTML in a container, read the form with FormData or querySelectorAll, convert the values to an Answer according to q.type, and call session.answer.

Ideas to extend it

  • Add partial credit for multiple questions (right selections minus wrong selections).
  • Add a timer per question using an injectable clock (see Project: Typing Speed Test).
  • Load questions from JSON and validate them with a Zod discriminated union.
  • Add 'ordering' and 'matching' question types and let the compiler guide you to each missing switch and scorer.
  • Store results in an array and show a history chart.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why model questions as a discriminated union instead of one interface with optional fields?

    With a tag like type, TypeScript narrows to the right member, so q.correct has the correct type in each branch.
  2. 2. What does the mapped type Scorers enforce?

    A mapped type over QuestionType creates one required key per member, so a new type without a scorer is a compile error.
  3. 3. What does Extract<Question, { type: K }> produce?

    Extract<T, U> keeps the members of T assignable to U.
  4. 4. What is the purpose of assertNever(q) in the default branch?

    If all cases are covered, q has type never there; otherwise the argument is not assignable to never.
  5. 5. Why does the session use a seeded random generator?

    The same seed always yields the same order, which makes behavior deterministic.

Summary

  • A discriminated union gives each question type exactly its own fields; the type tag narrows in switch and if.
  • Derive answer types and scorer signatures from the union with indexed access, Extract and mapped types.
  • A mapped type of scorers turns "I forgot a case" into a compile error.
  • Keep session state private and expose readonly snapshots such as QuizResult.
  • Use assertNever in default branches so adding a variant shows every place that needs updating.
  • Escape any content that goes into HTML, and use seeded randomness for testable shuffling.

Next: Project: Contact Manager