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 bothlengthvalues 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
- Change the second given answer from
nodetotscand confirm the score becomes 4 / 4. - Add a fifth question about
interfaceand a matching given reply that is correct. - 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.