TypeScript Tutorial

TypeScript Project: Quiz Game

A scored quiz from an array of questions. Print each prompt, check the answer, and tally.

What you will build

A quiz is a list of prompts and the string that counts as correct. You print a question, compare a given answer, add one to the score on a match, then print a short report. The list is a Question[]. The given answers in this tutorial are a fixed sequence so the output is the same every run.

That fixed sequence is the point of the demo: you can read the tally and know which items were right. ClickTry it in TypeScript to compile at /typescript/try. Do not paste this into Python or C++.

A Question interface

Each item needs a prompt and an answer. Keep both as string so a correct reply can be a word, not only a letter. One object is one question. The quiz will hold several.

Example

interface Question {
  prompt: string;
  answer: string;
}

const q: Question = {
  prompt: "How many bits in a byte?",
  answer: "8",
};

console.log(q.prompt);
console.log("Answer: " + q.answer);

Store the quiz in an array

Push each question onto an array. A loop can then print every prompt. The length of the quiz islength, so adding a question does not require a new array bound.

Example

interface Question {
  prompt: string;
  answer: string;
}

const quiz: Question[] = [];
quiz.push({ prompt: "How many bits in a byte?", answer: "8" });
quiz.push({ prompt: "TypeScript compiler command?", answer: "tsc" });
quiz.push({ prompt: "Keyword for a class field that callers cannot touch?", answer: "private" });

for (let i = 0; i < quiz.length; i++) {
  console.log(i + 1 + ". " + quiz[i].prompt);
}

Use Try it in TypeScript so this list opens in /typescript/try. Add a fourth prompt with push and confirm the numbering still starts at 1.

Check one answer

Compare the given string to question.answer. Exact match scores a point. This demo keeps comparisons case-sensitive so you see when a reply is almost right but not counted. A helper returns 1 or 0 so the tally is a running sum.

Example

interface Question {
  prompt: string;
  answer: string;
}

function mark(q: Question, given: string): number {
  if (given === q.answer) {
    console.log("Correct");
    return 1;
  }
  console.log("Wrong (expected " + q.answer + ")");
  return 0;
}

const q: Question = { prompt: "Capital of France?", answer: "Paris" };
console.log(q.prompt);
let score = 0;
score = score + mark(q, "Paris");
score = score + mark(q, "paris");
console.log("Score " + score);

First given answer matches. Second does not, because P and p differ. Score is 1.

Complete quiz with a fixed sequence

Pair each question with a given reply in a second array of the same length. Walk both with one index. Never callreadLine() here: the sequence is part of the program so the report is deterministic. A later version can fill given from the keyboard.

Example

interface Question {
  prompt: string;
  answer: string;
}

function mark(q: Question, given: string): number {
  console.log("You: " + given);
  if (given === q.answer) {
    console.log("Correct");
    return 1;
  }
  console.log("Wrong (expected " + q.answer + ")");
  return 0;
}

const quiz: Question[] = [];
quiz.push({ prompt: "How many bits in a byte?", answer: "8" });
quiz.push({ prompt: "TypeScript compiler command?", answer: "tsc" });
quiz.push({ prompt: "Keyword for a class field that callers cannot touch?", answer: "private" });
quiz.push({ prompt: "2 + 2?", answer: "4" });

const given: string[] = [];
given.push("8");
given.push("node");
given.push("private");
given.push("4");

let score = 0;
for (let i = 0; i < quiz.length; i++) {
  console.log(i + 1 + ". " + quiz[i].prompt);
  score = score + mark(quiz[i], given[i]);
}
console.log("Score: " + score + " / " + quiz.length);

Question 2 is wrong on purpose: the TypeScript compiler is tsc, not node. The report isScore: 3 / 4 every time you run this file.

Common mistakes

  • Letting the given-answer array run shorter than the quiz. Then given[i] isundefined. Check that both length values match, or store the reply on the interface.
  • Scoring with = instead of ===. Assignment does not compare strings.
  • Printing the expected answer before the player replies, then wondering why the quiz is not a quiz. Keep the key inside the object and print it only on a miss, as above, or hide it until you add typed input.
  • Mixing spaces in answers. "Paris " with a trailing space is not "Paris".

Practice

  1. Change the second given answer from node to tsc and confirm the score becomes 4 / 4.
  2. Add a fifth question about interface and a matching given reply that is correct.
  3. Print a percent: 100 * score / quiz.length, and if a given array is shorter than the quiz, print an error and skip scoring.

Next project: a library catalog you can search by author.

FAQ: TypeScript Project: Quiz Game

Common questions about this page.

What is the StudyGrid TypeScript tutorial?

The StudyGrid TypeScript tutorial follows the same chapter rhythm as C++: syntax, types, input, loops, functions, classes, generics, maps, and lambdas. Each chapter has copy-and-run examples.

Should I run typescript quiz project examples locally for better learning?

Yes. Use the browser editor on StudyGrid for a quick check, then Download the example and run it on your computer. Local runs show real errors and the real toolchain, which is one of the fastest ways to learn typescript quiz project in this TypeScript TypeScript lesson (TypeScript Project: Quiz Game).

Is the TypeScript editor the same as Try Python or Try C++?

No. Try TypeScript type-checks with tsc at /typescript/try and shows stdout plus compiler messages. Try Python stays at /try. Try C++ stays at /cpp/try. TypeScript lessons never open those editors.

Do I need to install a compiler to learn TypeScript?

No. Open a chapter, click Try it in TypeScript, and compile in the browser. You can also download a .ts file and compile locally with tsc.

Where should I start the TypeScript tutorial?

Start at TypeScript Intro, then Get Started and Syntax. After the first program, continue to output, variables, and if-else. After classes, open TypeScript Examples, then generics, Map, and arrow functions. Use Next at the bottom of each chapter.

Is the TypeScript tutorial free?

Yes. The TypeScript workshop on StudyGrid (studygrid.in) is free: dashboard, chapters, and the compile-and-run editor.